[英]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.