我有一个包含复合主键的表。
我正在对该表进行更新,在where子句中我需要主列的名称。 直到现在我一直在使用:
string sql = "SELECT PrimaryColumnName = col.column_name
FROM information_schema.table_constraints tc
INNER JOIN information_schema.key_column_usage col
ON col.Constraint_Name = tc.Constraint_Name
AND col.Constraint_schema = tc.Constraint_schema
WHERE tc.Constraint_Type = 'Primary Key'
AND col.Table_name = '" + TABLE NAME HERE + "'";
获取主键列。但是,如果主键是复合键,则会失败。 我如何在这里进行更新? 帮助
答案 0 :(得分:3)
以下查询将获取所有主键列:
SELECT c.Name
FROM [sys].[index_columns] ic
INNER JOIN [sys].[columns] c
ON ic.[object_id] = c.[object_id]
AND ic.[column_id] = c.[column_id]
INNER JOIN [sys].[indexes] i
ON i.[object_id] = ic.[object_id]
AND i.[index_id] = ic.[index_id]
WHERE i.is_primary_key = 1
AND ic.[object_id] = OBJECT_ID(@ObjectName);
<强> Example on SQL Fiddle 强>
正如评论中所指出的,您应该使用参数化查询。
答案 1 :(得分:1)
使用命令对象作为传递值作为SQL语句的参数,提供类型检查和验证
using (SqlConnection conn = new SqlConnection(sqlBuilder.ConnectionString))
{
string schemaName = "yourSchemaName";
string tableName = "yourTableName";
SqlCommand command = new SqlCommand(@"
SELECT column_name
FROM information_schema.key_column_usage
WHERE TABLE_SCHEMA = @schemaName AND TABLE_NAME = @tableName
AND OBJECTPROPERTY(object_id(constraint_name), 'IsPrimaryKey') = 1
ORDER BY table_schema, table_name", conn);
command.Parameters.Add("@schemaName", SqlDbType.VarChar, 100).Value = schemaName;
command.Parameters.Add("@tableName", SqlDbType.VarChar, 100).Value = tableName;
conn.Open();
SqlDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
{
Console.WriteLine(reader[0]);
}
}
finally
{
reader.Close();
}
}
答案 2 :(得分:0)
选择表名 然后按Alt + F1 您将获得所需的所有详细信息。
答案 3 :(得分:0)
您的查询似乎没问题。我已经测试了它并返回所有列主键是由。
尝试在SSMS中运行此功能,您将获得两个
CREATE TABLE dbo.T1
(
ID int NOT NULL,
SomeTextColumn nvarchar(30) NOT NULL,
SomeColumn nvarchar(20),
SomeOtherColumn uniqueidentifier,
CONSTRAINT [PK_T1] PRIMARY KEY CLUSTERED (ID, SomeTextColumn)
)
SELECT PrimaryColumnName = col.column_name
FROM information_schema.table_constraints tc
INNER JOIN information_schema.key_column_usage col ON col.Constraint_Name = tc.Constraint_Name
AND col.Constraint_schema = tc.Constraint_schema
WHERE tc.Constraint_Type = 'Primary Key' AND col.Table_name = 'T1'
这是一个SQL Fiddle示例。
如果您需要按列进行过滤,则可以随时添加“and col.COLUMN_NAME = 'ID'”