Question

I want to produce such output from my table. In fact I want create a function or procedure that get the name of the table and its columns (it also can be retrieved from sys.tables) and create such an output as a single string: imagine [tablename] has 3 row:

Tablename (code="1",column1="Column1value",column2="Column2value",column3="Column3value")
Tablename (code="2",column1="Column1value",column2="Column2value",column3="Column3value")
Tablename (code="3",column1="Column1value",column2="Column2value",column3="Column3value")
Was it helpful?

Solution

Try this Procedure to get the results in the required format.

CREATE Procedure GetTableValues(@tblname varchar(10))
As
BEGIN
DECLARE @idmin int,@idmax int,@colCnt int,@i int
DECLARE @outtbl TABLE(col1 varchar(1000))
DECLARE @tblval TABLE(col1 varchar(1000))
DECLARE @str varchar(1000),@colname varchar(100),@colvalue sql_variant
SET @str=''
SET @i=1
select @colCnt=COUNT(*) from sys.columns where object_id=object_id(@tblname)

IF EXISTS(select * from sys.tables where name='temp')
DROP TABLE temp
EXEC('select ROW_NUMBER() over (order by (select 0)) as rno,* into temp from '+@tblname)

select @idmin=MIN(rno),@idmax=MAX(rno) from temp

while(@idmin <=@idmax)
begin
while(@i <=@colCnt)
begin
select @colname=name from sys.columns where column_id=@i and object_id=object_id(@tblname)
insert into @tblval 
exec('select '+@colname+' from temp where rno='+@idmin)
select @colvalue=col1 from @tblval  
SET @str=@str+','+@colname+'="'+cast(@colvalue as varchar)+'"' 
SET @i=@i+1
end
insert into @outtbl 
select @tblname+'('+STUFF(@str,1,1,'')+')'
SET @idmin=@idmin+1
SET @i=1
SET @str=''
end
select * from @outtbl 
END


exec GetTableValues 'test7'

OTHER TIPS

We can get column names of the passed table name from sys table, and then to print table values for each row, we can use ROW_NUMBER and print the string by appending column values for each rows and get the final output. There would be to For each loop nested. Outer foreach loop will use ROW_NYMBER and will be executed for all rows in the table and inner loop will print column values in one string as required.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top