简体   繁体   English

如何获取表的PRIMARY KEY列名

[英]How to get PRIMARY KEY column name of a table

I need to get the PRIMARY KEY COLUMN NAME. 我需要获得PRIMARY KEY COLUMN NAME。 I have the name of my table in a variable called _lstview_item 我在一个名为_lstview_item的变量中有我的表名

Till now i tried getting the column name like this 直到现在我尝试获取这样的列名

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

Without any success. 没有任何成功。 Help ? 救命 ?

this should be your query. 这应该是你的查询。 You are missing single quotes on your table name. 您在表名上缺少单引号。 Tested and works fine. 经过测试,工作正常。

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 + "'";

try this: 试试这个:

SELECT column_name
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE OBJECTPROPERTY(OBJECT_ID(constraint_name), 'IsPrimaryKey') = 1
AND table_name = 'TableName'

I know it's already solved but I did it this way. 我知道它已经解决但我这样做了。 Tested with MSSQL and MYSQL and it works perfectly. 经过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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM