将列的名称添加到我的选择结果中

时间:2012-08-05 10:52:12

标签: sql sql-server-2008-r2 bibtex bibliography

我想从我的表中产生这样的输出。实际上我想创建一个函数或过程来获取表及其列的名称(它也可以从sys.tables中检索) 并创建一个单个字符串输出: imagine [tablename]有3行:

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

2 个答案:

答案 0 :(得分:0)

我们可以从sys表中获取传递的表名的列名,然后为每行打印表值,我们可以使用ROW_NUMBER并通过为每行附加列值来打印字符串并获得最终输出。将嵌套的每个循环。外部foreach循环将使用ROW_NYMBER并将对表中的所有行执行,内部循环将根据需要在一个字符串中打印列值。

答案 1 :(得分:0)

尝试此程序以获得所需格式的结果。

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'