日期:2014-05-18  浏览次数:20766 次

SQL存储过程,循环每列
我想用存储过程循环出每列的值,比如传入一个ID,返回这条ID的所有字段组合的字符串。
比如表TAB1,字段有:ID,A1,A2,A3,A4,我想实现的效果是传入一个ID,返回:A1|A2|A3|A4,这样的值。

------解决方案--------------------
SQL code

create proc pt
@id int,
@retval nvarchar(max) output
as
begin
    declare @sql nvarchar(max);    
    select @sql=isnull(@sql,'select @retval=')+c.name+'+''|''+'
        from syscolumns c,sysobjects o,systypes t
        where c.id =o.id and o.name='TAB1'
        and c.xtype=t.xtype and t.name in('char','varchar','nchar','nvarchar');
    select @sql=substring(@sql,1,len(@sql)-5)+' from TAB1 where ID='+cast(@id as nvarchar(20));
    exec sp_executesql @sql,N'@retval nvarchar(max) output',@retval output
end
go

declare @retval nvarchar(max)
exec pt 1,@retval output
select @retval;

------解决方案--------------------
--取字段
create table testtb (id int identity(1,1),A varchar(30),B varchar(30),C varchar(30))
insert into testtb(A,B,C)
select 'a','b','c'
insert into testtb(A,B,C)
select 'aa','bb','cc'
declare @s varchar(max)
set @s =''
SELECT @s += NAME +'|' FROM syscolumns WHERE ID=OBJECT_ID('testtb')
SELECT @s
drop table testtb
go
--或者(取内容)
create table testtb (id int identity(1,1),A varchar(30),B varchar(30),C varchar(30))
insert into testtb(A,B,C)
select 'a','b','c'
insert into testtb(A,B,C)
select 'aa','bb','cc'
declare @s varchar(max)
declare @sql nvarchar(max)
set @sql=''
set @s =''--必须初始化
SELECT @s += NAME +'+'+'''|''' +'+'FROM syscolumns WHERE ID=OBJECT_ID('testtb')
set @s = SUBSTRING(@s,0,LEN(@s))
set @s = SUBSTRING(@s,CHARINDEX('+',@s,0)+5,len(@s))
select @sql =N'select '+@s +' from testtb where id =2' --根据ID查询
exec (@sql)
drop table testtb