循环浏览当前表以查找列是否为主键?

时间:2019-03-26 17:35:12

标签: sql sql-server ssms-2016

我有一个名为#ColumnList的临时表,其中包含列名称列表。我需要遍历该表中的每一行,并查看该列是否为主键。如果它是键,那么我需要将该列名称添加到名为PRIMARYKEYCOLUMN的列中。

这是我到目前为止所拥有的,但是没有用。抛出错误

  

无法将值NULL插入表'tempdb.dbo。#ColumnList __________________ 0000000B0D8C'的'DataType'列中;列不允许为空。 INSERT失败。

ALTER TABLE #ColumnList
ADD PRIMARYKEYCOLUMN VARCHAR(50);

INSERT INTO #ColumnList ([PRIMARYKEYCOLUMN])
(SELECT DISTINCT KU.column_name as PRIMARYKEYCOLUMN 
FROM 
sys.columns c 
       JOIN sys.types t ON t.user_type_id = c.user_type_id
                        AND t.system_type_id = c.system_type_id      
JOIN sys.tables tab ON c.object_id = tab.object_id
JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS TC ON TC.TABLE_NAME = tab.name 
INNER JOIN
    INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KU
          ON TC.CONSTRAINT_TYPE = 'PRIMARY KEY' AND
             TC.CONSTRAINT_NAME = KU.CONSTRAINT_NAME AND 
             KU.table_name='myTableName'    
JOIN #ColumnList cl ON cl.ColumnName = KU.COLUMN_NAME)

上面的子查询(没有JOIN #ColumnList cl ON cl.ColumnName = KU.COLUMN_NAME)可以正常工作,并返回以下结果。但是插入无法正常工作。

[PRIMARYKEYCOLUMN]
Column1
Column2
Column3

我需要将上面相同的列插入到具有相同列名的临时表中

1 个答案:

答案 0 :(得分:2)

更新语句可能会起作用,例如:

update
    #ColumnList  
set
    PRIMARYKEYCOLUMN = ColumnName 
where
    ColumnName in (
        SELECT
            DISTINCT KU.column_name  
        FROM
            sys.columns c         
        JOIN
            sys.types t 
                ON t.user_type_id = c.user_type_id                         
                AND t.system_type_id = c.system_type_id       
        JOIN
            sys.tables tab 
                ON c.object_id = tab.object_id 
        JOIN
            INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS TC 
                ON TC.TABLE_NAME = tab.name  
        INNER JOIN
            INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KU           
                ON TC.CONSTRAINT_TYPE = 'PRIMARY KEY' 
                AND              TC.CONSTRAINT_NAME = KU.CONSTRAINT_NAME 
                AND               KU.table_name='myTableName'
        )