2

我有一个具有复合主键的表。

我正在对该表进行更新,并且在 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 + "'";

获取主键列。但是,如果主键是复合的,它就会失败。我如何在这里进行更新?帮助。

4

4 回答 4

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);

SQL Fiddle 示例

正如评论中所指出的,您应该使用参数化查询。

于 2013-09-02T07:37:19.977 回答
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();
      }

 }
于 2013-09-02T09:43:01.657 回答
0

选择表名并按 Alt+F1 您将获得所需的所有详细信息。

于 2013-09-02T06:39:44.487 回答
0
于 2013-09-02T15:18:02.413 回答