如何将主键添加到SQL Server中的所有表?

时间:2018-02-13 06:18:31

标签: sql sql-server

从MS Access迁移到SQL Server然后使用Entity Framework时,我遇到了这个问题。没有一个表具有主键,这是将它们导入实体框架模型所必需的。

2 个答案:

答案 0 :(得分:0)

{{1}}

好处是,如果某个表失败,它就不会失败。

答案 1 :(得分:0)

试试这个

DECLARE @Qry NVARCHAR(MAX)
;WITH CTE
AS
(
SELECT  
    Qry = 
       'IF NOT EXISTS(SELECT 1 FROM sys.columns WHERE name =''SeqNo'' AND [object_id] = OBJECT_ID('''+T.TABLE_SCHEMA+'.'+T.TABLE_NAME+'''))
       BEGIN
          ALTER TABLE '+T.TABLE_SCHEMA+'.'+T.TABLE_NAME+'
          ADD SeqNo INT IDENTITY(1,1) CONSTRAINT Pk_'+T.TABLE_NAME+'_SeqNo PRIMARY KEY
       END
       GO
       '
    FROM INFORMATION_SCHEMA.TABLES T 
       LEFT JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS C
          ON T.TABLE_NAME = C.TABLE_NAME
             AND T.TABLE_SCHEMA = C.TABLE_SCHEMA
             AND T.TABLE_CATALOG = C.TABLE_CATALOG
             AND C.CONSTRAINT_TYPE = 'PRIMARY KEY'
          WHERE C.CONSTRAINT_NAME IS NULL
             AND T.TABLE_TYPE = 'BASE TABLE'
)
SELECT 
    @Qry = STUFF((
    SELECT ' ' + Qry
    FROM CTE
    FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')

EXEC @Qry