日期:2014-05-18 浏览次数:20783 次
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