Thursday, 22 August 2013

How to get PRIMARY KEY column name of a table

How to get PRIMARY KEY column name of a table

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 ?

No comments:

Post a Comment