[英]How to get PRIMARY KEY COLUMNS of a table (in case of COMPOSITE primary key)
[英]How to get PRIMARY KEY column name of a table
我需要获得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();
没有任何成功。 救命 ?
这应该是你的查询。 您在表名上缺少单引号。 经过测试,工作正常。
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 + "'";
试试这个:
SELECT column_name
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE OBJECTPROPERTY(OBJECT_ID(constraint_name), 'IsPrimaryKey') = 1
AND table_name = 'TableName'
我知道它已经解决但我这样做了。 经过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.