Monday, 6 January 2014

FUNCTION TO concatenate all COLUMNS OF a TABLE

FUNCTION TO concatenate all COLUMNS OF a TABLE 

USE AdventureWorksDW2008
GO

CREATE FUNCTION fn_columns( @tblname varchar(50))
returns varchar(MAX)
as
BEGIN
DECLARE @name VARCHAR(500)=''
SELECT @name=name+', '+@name FROM SYS.columns WHERE OBJECT_ID=OBJECT_ID(@tblname)
RETURN left(@NAME,len(@NAME)-1)
END

 SELECT NAME,dbo.fn_columns(name)as COLUMNS from sys.tables

EMP, DEPT Sample script

/****** Object:  Table [dbo].[DEPT]    Script Date: 19-05-2016 06:58:37 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO SET A...