Skip to content

Instantly share code, notes, and snippets.

@RickyLin
Created September 15, 2020 07:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RickyLin/49c40ceb37be9c4c01a69780d2d81f21 to your computer and use it in GitHub Desktop.
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
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