Search code examples
sqlsql-server-2008-r2bibtexbibliography

add columns names to the result of my select from text


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")

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'