如何获取表的PRIMARY KEY列名

时间:2013-08-22 08:25:33

标签: c# asp.net primary-key

我需要获得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();

没有任何成功。 帮忙?

3 个答案:

答案 0 :(得分:7)

这应该是你的查询。您在表名上缺少单引号。经过测试并且工作正常。

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 + "'";

答案 1 :(得分:5)

试试这个:

SELECT column_name
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE OBJECTPROPERTY(OBJECT_ID(constraint_name), 'IsPrimaryKey') = 1
AND table_name = 'TableName'

答案 2 :(得分:1)

我知道它已经解决了,但是我是这样做的。 经过MSSQL和MYSQL测试,效果很好。

with Asset_Data_Historical(AssetID, Data_Received_On) as
(
  select 17085, timestamp'2017-08-23 22:50:00' from dual union all
  select 17085, timestamp'2017-08-25 20:54:00' from dual union all 
  select 17085, timestamp'2017-08-25 21:08:00' from dual union all 
  select 17085, timestamp'2017-08-31 18:49:00' from dual union all  
  select 17085, timestamp'2017-09-29 18:51:00' from dual    
), Customer_Contacted_Logs(TicketID, Asset_ID, Last_Contacted_On ) as
(
  select 1785487,17085, timestamp'2017-09-28 21:57:00' from dual union all
  select 1785491,17085, timestamp'2017-10-16 18:51:00' from dual
)
select a.*, 
      ( select min(c.Last_Contacted_On)
          from Customer_Contacted_Logs c 
         where a.AssetID = c.Asset_ID
           and a.Data_Received_On < c.Last_Contacted_On )
       as Last_Contacted_On
  from Asset_Data_Historical a;


ASSETID   DATA_RECEIVED_ON      LAST_CONTACTED_ON
17085     23.08.2017 22:50:00   28.09.2017 21:57:00
17085     25.08.2017 20:54:00   28.09.2017 21:57:00
17085     25.08.2017 21:08:00   28.09.2017 21:57:00
17085     31.08.2017 18:49:00   28.09.2017 21:57:00
17085     29.09.2017 18:51:00   16.10.2017 18:51:00