7

PRIMARY KEY COLUMN NAME を取得する必要があります。という変数にテーブルの名前があります_lstview_item

今まで私はこのような列名を取得しようとしました

 string sql = "SELECT ColumnName = 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 = " +_lstview_item+ "";

 SqlConnection conn2 = new SqlConnection(cc.connectionString(cmb_dblist.Text));
 SqlCommand cmd_server2 = new SqlCommand(sql);
 cmd_server2.CommandType = CommandType.Text;
 cmd_server2.Connection = conn2;
 conn2.Open();
 string ColumnName = (string)cmd_server2.ExecuteScalar();                 
 conn2.Close();

成功せずに。ヘルプ ?

4

3 に答える 3

9

これがクエリになります。テーブル名に一重引用符がありません。テスト済みで正常に動作します。

string sql = "SELECT ColumnName = 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 = '" + _lstview_item + "'";
于 2013-08-22T08:34:47.027 に答える
8

これを試して:

SELECT column_name
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE OBJECTPROPERTY(OBJECT_ID(constraint_name), 'IsPrimaryKey') = 1
AND table_name = 'TableName'
于 2013-08-22T08:31:31.167 に答える