Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 222
Anoushka Seechurn Avatar asked Aug 22 '13 08:08

Anoushka Seechurn


3 Answers

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 + "'";
like image 90
Ehsan Avatar answered Nov 18 '22 10:11

Ehsan


try this:

SELECT column_name
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE OBJECTPROPERTY(OBJECT_ID(constraint_name), 'IsPrimaryKey') = 1
AND table_name = 'TableName'
like image 27
xrodas Avatar answered Nov 18 '22 10:11

xrodas


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;
}
like image 2
Michaël Randria Avatar answered Nov 18 '22 09:11

Michaël Randria