I'm trying to construct the ALTER TABLE statements for multiple tables for adding PRIMARY KEY constraints. For example:
ALTER TABLE dbo.Employee_Info ADD PRIMARY KEY (EmployeeID, Employee_Name);
I'm able to get the list of PK columns for a given table using INFORMATION_SCHEMA objects:
SELECT Col.Column_Name from
INFORMATION_SCHEMA.TABLE_CONSTRAINTS Tab,
INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE Col
WHERE
Col.Constraint_Name = Tab.Constraint_Name
AND Col.Table_Name = Tab.Table_Name
AND Constraint_Type = 'PRIMARY KEY'
AND Col.Table_Name = 'Employee_Info'
Output:
Column_Name
EmployeeID
Employee_Name
But I need to concatenate the resultant output column lists into a single line in order for me to use it in my ALTER statement's ADD PRIMARY KEY clause as shown at the top.
I tried to use COALESCE
as shown below:
DECLARE @pkcols varchar(100)
BEGIN
SET @pkcols = (SELECT @pkcols = COALESCE(@pkcols + ', ', '') + Column_Name
FROM (
SELECT Col.Column_Name from
INFORMATION_SCHEMA.TABLE_CONSTRAINTS Tab,
INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE Col
WHERE
Col.Constraint_Name = Tab.Constraint_Name
AND Col.Table_Name = Tab.Table_Name
AND Constraint_Type = 'PRIMARY KEY'
AND Col.Table_Name = 'Employee_Info' ))
END
but it keeps throwing an error:
Incorrect syntax near '@pkcols'.
I'm not sure how to solve this issue and get the list of columns in a single line so that I can use it in my automation.
Can someone please help?