要使用ADO.NET查找表的主键列,请遵循以下步骤:
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE OBJECTPROPERTY(OBJECT_ID(CONSTRAINT_SCHEMA + '.' + CONSTRAINT_NAME), 'IsPrimaryKey') = 1 AND TABLE_NAME = 'YourTableName'
以下是一个C#代码示例:
using System;
using System.Data.SqlClient;
using System.Collections.Generic;
class Program
{
static void Main()
{
string connectionString = "your_connection_string";
string tableName = "YourTableName";
List<string> primaryKeyColumns = GetPrimaryKeyColumns(connectionString, tableName);
foreach (string column in primaryKeyColumns)
{
Console.WriteLine("Primary Key Column: " + column);
}
}
static List<string> GetPrimaryKeyColumns(string connectionString, string tableName)
{
List<string> primaryKeyColumns = new List<string>();
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE OBJECTPROPERTY(OBJECT_ID(CONSTRAINT_SCHEMA + '.' + CONSTRAINT_NAME), 'IsPrimaryKey') = 1 AND TABLE_NAME = @TableName", connection))
{
command.Parameters.AddWithValue("@TableName", tableName);
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
primaryKeyColumns.Add(reader.GetString(0));
}
}
}
}
return primaryKeyColumns;
}
}
这个示例将连接到数据库,执行查询以获取表的主键列,并将结果存储在列表中。然后,它将遍历列表并打印每个主键列的名称。
领取专属 10元无门槛券
手把手带您无忧上云