if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[p_sql]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[p_sql]
GO
--生成处理临时表
select id=identity(int,1,1),gid=0
,fdname,sv=case
when type like '%int' or type like '%money'
or type in('float','real','decimal','numeric')
then 'case when '+fdname+' is null then ''NULL'' else convert(varchar,'+fdname+') end'
when type like '%datetime' or type like '%binary'
or type in('timestamp','uniqueidentifier')
then 'case when '+fdname+' is null then ''NULL'' else ''''''''+replace(convert(varchar,'+fdname+'),'''''''','''''''''''')+'''''''' end'
else 'case when '+fdname+' is null then ''NULL'' else ''''''''+replace('+fdname+','''''''','''''''''''')+'''''''' end'
end
into # from(
select fdname='['+replace(a.name,']',']]')+']'
,type=b.name,a.colid
from syscolumns a
join systypes b on a.xtype=b.xtype
where b.name not in('image','ntext','text','sql_variant') --不能处理的类型
and id=object_id(@tbname)
)a order by colid
if @@rowcount=0 return --如果没有满足条件的数据,退出
--判断需要多少个变量来处理
select @i=max(len(sv)) from #
set @i=3800/@i
--分组临时表
update # set gid=id/@i
select @i=max(gid) from #
while @i>=0
select @ic=cast(@i as varchar),@i=@i-1
,@sql1='@a'+@ic+' nvarchar(4000),@b'+@ic+' nvarchar(4000),'+@sql1
,@sql2='@a'+@ic+'='''',@b'+@ic+'='''','+@sql2
,@sql3='select @a'+@ic+'=@a'+@ic+'+'',''+fdname,@b'
+@ic+'=@b'+@ic+'+''+'''',''''+''+sv from # where gid='+@ic+char(13)+@sql3
,@sql41='+@a'+@ic+@sql41
,@sql42='+@b'+@ic+@sql42