2008-06-03

COOL SP: Get comma separated column names

This one is really useful.
There is one parameter where U set table name.
Result is in messages tab, so don't expect a resultset.


IF object_id(N'dbo.TECH_Columns', N'P') IS NOT NULL DROP PROCEDURE dbo.TECH_Columns
GO

CREATE PROCEDURE dbo.TECH_Columns
@table varchar(100) = ''
AS
BEGIN
SET NOCOUNT ON

DECLARE @s nvarchar(max)
SET @s = ''
SELECT @s = @s + column_name+', '
FROM information_schema.columns
WHERE table_name LIKE @table
ORDER BY ordinal_position

PRINT LEFT(@s, LEN(@s)-2)
END
GO

This Stored Procedure uses Information schema view: information_schema.columns to retrieve columns for table. Another way is to use system view sys.all_columns but information_schema views are more human readable.

No comments: