SET NOCOUNT ON
;WITH CTE
AS(
SELECT TABLE_NAME,CONSTRAINT_NAME AS RO, COLUMN_NAME AS VAL
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE OBJECTPROPERTY(OBJECT_ID(CONSTRAINT_NAME), 'ISPRIMARYKEY') = 1
)
SELECT DISTINCT 'IF NOT EXISTS(SELECT TOP 1 1 FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE' + CHAR(10) +
'WHERE CONSTRAINT_NAME=''' + RO + '''' + CHAR(10) +
'AND TABLE_NAME = ''' + TABLE_NAME + ''')' + CHAR(10) +
'BEGIN' + CHAR(10) + CHAR(9) +
'ALTER TABLE '+ TABLE_NAME + CHAR(10) + CHAR(9) +
'ADD CONSTRAINT ' + RO + ' PRIMARY KEY ('+D.VAL+')' + CHAR(10) +
'END' + CHAR(10) +
'ELSE' + CHAR(10) +
'BEGIN' + CHAR(10) + CHAR(9) +
'SELECT ''' + RO + ' ALREADY EXISTS.''' + CHAR(10) +
'END' + CHAR(10)
FROM CTE P1
CROSS APPLY ( SELECT
STUFF( (SELECT ','+VAL
FROM CTE P2
WHERE P2.RO = P1.RO
ORDER BY RO
FOR XML PATH(''), TYPE).value('.', 'VARCHAR(MAX)')
,1,1,'')
) D ( VAL )
SET NOCOUNT OFF
;WITH CTE
AS(
SELECT TABLE_NAME,CONSTRAINT_NAME AS RO, COLUMN_NAME AS VAL
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE OBJECTPROPERTY(OBJECT_ID(CONSTRAINT_NAME), 'ISPRIMARYKEY') = 1
)
SELECT DISTINCT 'IF NOT EXISTS(SELECT TOP 1 1 FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE' + CHAR(10) +
'WHERE CONSTRAINT_NAME=''' + RO + '''' + CHAR(10) +
'AND TABLE_NAME = ''' + TABLE_NAME + ''')' + CHAR(10) +
'BEGIN' + CHAR(10) + CHAR(9) +
'ALTER TABLE '+ TABLE_NAME + CHAR(10) + CHAR(9) +
'ADD CONSTRAINT ' + RO + ' PRIMARY KEY ('+D.VAL+')' + CHAR(10) +
'END' + CHAR(10) +
'ELSE' + CHAR(10) +
'BEGIN' + CHAR(10) + CHAR(9) +
'SELECT ''' + RO + ' ALREADY EXISTS.''' + CHAR(10) +
'END' + CHAR(10)
FROM CTE P1
CROSS APPLY ( SELECT
STUFF( (SELECT ','+VAL
FROM CTE P2
WHERE P2.RO = P1.RO
ORDER BY RO
FOR XML PATH(''), TYPE).value('.', 'VARCHAR(MAX)')
,1,1,'')
) D ( VAL )
SET NOCOUNT OFF
No comments:
Post a Comment