编程语言
首页 > 编程语言> > 首页> C#>如何获取表和主键,并显示空,如果表没有主键?

首页> C#>如何获取表和主键,并显示空,如果表没有主键?

作者:互联网

我目前正在尝试通过在C#中调用以下SQL来检索每个表的表名和主键.到目前为止,这是我尝试过的:

SELECT t.TABLE_NAME As 'Table Name',
       Keys.COLUMN_NAME AS 'Primary Key'
FROM INFORMATION_SCHEMA.TABLES t 
left outer join INFORMATION_SCHEMA.TABLE_CONSTRAINTS Constraints
         on  t.TABLE_NAME = Constraints.Table_name 
         and t.Table_Schema = Constraints.Table_Schema 
left outer join INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS Keys 
         ON  Constraints.TABLE_NAME = Keys.TABLE_NAME 
         and Constraints.CONSTRAINT_NAME = Keys.CONSTRAINT_NAME 
         and Constraints.CONSTRAINT_TYPE = 'PRIMARY KEY'

问题是,如果表没有主键,我希望结果只包含一个“空”条目.在工作时,由于某种原因,结果包含“ Salary”表的重复项,如下所示. Salary和Employees表都具有主键,而“ Test”表则没有:

编辑:我现在已经尝试过了,它似乎可以工作.这样做有什么不利之处吗?

SELECT T.TABLE_NAME As 'Table Name'
    ,       (
            Select K1.COLUMN_NAME
            From INFORMATION_SCHEMA.TABLE_CONSTRAINTS As C1
                Join INFORMATION_SCHEMA.KEY_COLUMN_USAGE As K1
                    On C1.TABLE_SCHEMA = K1.TABLE_SCHEMA
                        And C1.TABLE_NAME = K1.TABLE_NAME 
                        And C1.CONSTRAINT_NAME = K1.CONSTRAINT_NAME 
            Where C1.CONSTRAINT_TYPE = 'PRIMARY KEY'
                And T.TABLE_SCHEMA = C1.TABLE_SCHEMA 
                And T.TABLE_NAME = C1.TABLE_NAME 
            )As PrimaryKeyColumns
FROM INFORMATION_SCHEMA.TABLES As T 

解决方法:

尝试替换此条件Constraints.CONSTRAINT_TYPE =’PRIMARY KEY’:

SELECT t.TABLE_NAME As 'Table Name',
       Keys.COLUMN_NAME AS 'Primary Key'
FROM INFORMATION_SCHEMA.TABLES t 
left outer join INFORMATION_SCHEMA.TABLE_CONSTRAINTS Constraints
         on  t.TABLE_NAME = Constraints.Table_name 
         and t.Table_Schema = Constraints.Table_Schema  
         and Constraints.CONSTRAINT_TYPE = 'PRIMARY KEY'       
left outer join INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS Keys 
         ON  Constraints.TABLE_NAME = Keys.TABLE_NAME 
         and Constraints.CONSTRAINT_NAME = Keys.CONSTRAINT_NAME 

标签:information-schema,sql-server-2008,sql,c,sql-server
来源: https://codeday.me/bug/20191031/1979306.html