Thursday, May 27, 2021

Display column names separated with comma

We can achieve this by STUFF Function. I have used it as stored procedure.

See Detail about STUFF Function: STUFF Function with example

SQL Code:

CREATE PROCEDURE TableColumns (@Table VARCHAR(100))
AS
SELECT ColumnNames =
STUFF( (SELECT ', ' + c.name
FROM
sys.columns c
INNER JOIN
sys.types t ON c.user_type_id = t.user_type_id
WHERE
c.object_id = OBJECT_ID( @Table)
FOR XML PATH('')),
1, 1, '')
GO

Execute and run the above store procedure.

exec TableColumns 'Employee_Details'

Output:

ColumnNames

 EmployeeId, Name, SSN, DepartmentCode, IntraDepartmentCode


No comments:

Post a Comment