关于NVARCHAR(4000) 字符串过少的问题

xhunanpp 2004-06-21 02:14:46
问题如下:
DECLARE @Str nvarchar(4000) --ntext,
@Str = 'SQL... 语句'
@Str = @Str + 'SQL... 语句'

exec @Str

以上SQL 有一个难题, 我现在的SQL 语句的字符串超过4000个字符串,
我改成 DECLARE @Str ntext ,但ntext 不能垒加啊, 有办法解决吗?
--------------

...全文
125 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
CsdnRob 2004-07-02
  • 打赏
  • 举报
回复
faint 我要的就是“鱼”,不是“渔”。 懒得多说了, 非切题者勿灌 ( ^_^,口气大了)
zjcxc 元老 2004-06-21
  • 打赏
  • 举报
回复
用临时表有问题吗?

那你在前台生成SQL语句,这样就不存在超长的问题了.
xhunanpp 2004-06-21
  • 打赏
  • 举报
回复
还有没有不用临时表的方法??
zjcxc 元老 2004-06-21
  • 打赏
  • 举报
回复
--解决办法

declare @sqlhead nvarchar(4000),@sqlend nvarchar(4000)
,@sql1 nvarchar(4000),@sql2 nvarchar(4000),@sql3 nvarchar(4000),@sql4 nvarchar(4000)
,@i int,@ic varchar(20)

--生成数据处理临时表
select id=identity(int,0,1),gid=0
,a=',['+单位名称 +']=sum(case 单位名称 when '''
+单位名称+''' then 销售额 else 0 end)'
into # from(select distinct 单位名称 from tb) a

--判断需要多少个变量来处理
select @i=max(len(a)) from #
set @i=3800/@i

--分组临时表
update # set gid=id/@i
select @i=max(gid) from #

--生成数据处理语句
select @sqlhead='''select 日期=convert(varchar(10),日期,120)'''
,@sqlend=''' from tb group by convert(varchar(10),日期,120)'''
,@sql1='',@sql2='select ',@sql3='',@sql4=''

while @i>=0
select @ic=cast(@i as varchar),@i=@i-1
,@sql1='@'+@ic+' nvarchar(4000),'+@sql1
,@sql2=@sql2+'@'+@ic+'='''','
,@sql3='select @'+@ic+'=@'+@ic+'+a from # where gid='+@ic
+char(13)+@sql3
,@sql4=@sql4+',@'+@ic

select @sql1='declare '+left(@sql1,len(@sql1)-1)+char(13)
,@sql2=left(@sql2,len(@sql2)-1)+char(13)
,@sql3=left(@sql3,len(@sql3)-1)
,@sql4=substring(@sql4,2,4000)

--执行
exec( @sql1+@sql2+@sql3+'
exec('+@sqlhead+'+'+@sql4+'+'+@sqlend+')'
)

--删除临时表
drop table #
zjcxc 元老 2004-06-21
  • 打赏
  • 举报
回复
/*-- 数据测试环境 --*/
if exists (select * from dbo.sysobjects where id = object_id(N'[tb]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [tb]
GO

create table tb(单位名称 varchar(10),日期 datetime,销售额 int)
insert into tb
select 'A单位','2001-01-01',100
union all select 'B单位','2001-01-02',101
union all select 'C单位','2001-01-03',102
union all select 'D单位','2001-01-04',103
union all select 'E单位','2001-01-05',104
union all select 'F单位','2001-01-06',105
union all select 'G单位','2001-01-07',106
union all select 'H单位','2001-01-08',107
union all select 'I单位','2001-01-09',108
union all select 'J单位','2001-01-11',109

/*-- 要求结果
日期 A单位 B单位 C单位 D单位 E单位 F单位 G单位 H单位 I单位 J单位
---------- ----- ----- ----- ----- ----- ----- ---- ---- ---- ------
2001-01-01 100 0 0 0 0 0 0 0 0 0
2001-01-02 0 101 0 0 0 0 0 0 0 0
2001-01-03 0 0 102 0 0 0 0 0 0 0
2001-01-04 0 0 0 103 0 0 0 0 0 0
2001-01-05 0 0 0 0 104 0 0 0 0 0
2001-01-06 0 0 0 0 0 105 0 0 0 0
2001-01-07 0 0 0 0 0 0 106 0 0 0
2001-01-08 0 0 0 0 0 0 0 107 0 0
2001-01-09 0 0 0 0 0 0 0 0 108 0
2001-01-11 0 0 0 0 0 0 0 0 0 109
--*/
zjcxc 元老 2004-06-21
  • 打赏
  • 举报
回复
用多个变量实现就可以了.

34,590

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧