7

我需要获取主键列名。我在一个名为的变量中有我的表的名称_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 回答
2

我知道它已经解决了,但我是这样做的。用 MSSQL 和 MYSQL 测试过,效果很好。

public static List<string> GetPrimaryKeyColumns(DbConnection connection, string tableName)
{
        List<string> result = new List<string>();
        DbCommand command = connection.CreateCommand();
        string[] restrictions = new string[] { null, null, tableName };
        DataTable table = connection.GetSchema("IndexColumns", restrictions);

        if (string.IsNullOrEmpty(tableName))
            throw new Exception("Table name must be set.");

        foreach (DataRow row in table.Rows)
        {
            result.Add(row["column_name"].ToString());
        }

        return result;
}
于 2019-03-24T08:36:40.633 回答