I need to get the PRIMARY KEY COLUMN NAME.
I have the name of my table in a variable called _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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With