Created
September 15, 2020 07:31
-
-
Save RickyLin/49c40ceb37be9c4c01a69780d2d81f21 to your computer and use it in GitHub Desktop.
Generate SQL scripts that create primary key for tables that have no primary key defined but have identity column
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
SELECT T.*, PK.COLUMN_NAME | |
INTO #Tables | |
FROM INFORMATION_SCHEMA.TABLES T | |
INNER JOIN ( | |
SELECT TABLE_NAME, COLUMN_NAME | |
FROM INFORMATION_SCHEMA.COLUMNS | |
WHERE COLUMNPROPERTY(OBJECT_ID(TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1 | |
) PK ON PK.TABLE_NAME = T.TABLE_NAME | |
WHERE T.TABLE_TYPE = 'BASE TABLE' | |
AND T.TABLE_NAME NOT IN ( | |
SELECT TABLE_NAME | |
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS | |
WHERE CONSTRAINT_TYPE = 'PRIMARY KEY' | |
) | |
DECLARE @SqlScripts NVARCHAR(MAX) | |
SET @SqlScripts = '' | |
SELECT @SqlScripts = @SqlScripts + 'ALTER TABLE ' + TABLE_SCHEMA + '.' + TABLE_NAME + ' ADD CONSTRAINT PK_' + TABLE_NAME | |
+ ' PRIMARY KEY CLUSTERED ( ' + COLUMN_NAME + ' ) | |
' | |
FROM #Tables | |
SELECT @SqlScripts | |
DROP TABLE #Tables |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment