Home  >  Article  >  Database  >  如何解决动态查询语句太长,大于数据库字符的最大长度

如何解决动态查询语句太长,大于数据库字符的最大长度

WBOY
WBOYOriginal
2016-06-07 15:13:591895browse

上周,在写sql server2005 数据库 存储过程的时候,用到了 动态 查询 语句 ,但是由于 语句 太长,定义的变量最长为varchar(8000),在 字符 串 大于 8000的时候, 数据库 会做截断,进而在执行 动态 语句 时报错。 未 解决 此问题,找到了定义变量的 长度 var

   上周,在写sql server2005数据库存储过程的时候,用到了动态查询语句,但是由于语句太长,定义的变量最长为varchar(8000),在字符大于8000的时候,数据库会做截断,进而在执行动态语句时报错。


   未解决此问题,找到了定义变量的长度varchar(max),基本语句如下:


   declare

       @v_cmdstr1    varchar(max)
      ,@v_cmdstr2    varchar(8000)


   set @v_cmdstr1='select row_number()over (order by a.i_branch_no,a.vc_no) rn
           ,a.i_branch_no,b.bname as branch_name,a.vc_no
           ,c.vc_name,a.i_begin_date,a.i_end_date'
   select @v_cmdstr1=@v_cmdstr1+',sum(case when a.c_relate_type='+convert(char(5),c_relate_type)
           +' and a.vc_pro_code='+convert(varchar(32),vc_pro_code)
           +' and a.vc_item_code='+convert(varchar(32),vc_item_code)
           +' then isnull(a.en_occur_balance,0) else 0 end) as '+title_name
      from (select top 500 c_relate_type,vc_pro_code,vc_item_code,title_name
                        from #check) t
   set @v_cmdstr2=' into ##transitem from ##checkit a
           left join seclose..branch b on a.i_broker_no=b.bid
           left join sm..tb_operators c on a.vc_no = c.vc_no
           group by a.i_branch_no,b.bname,a.vc_no
           ,c.vc_name,a.i_begin_date,a.i_end_date'
 exec(@v_cmdstr1+@v_cmdstr2);


   理论上,将变量 @v_cmdstr1 定义为  varchar(max)之后,最大字符串可为2G,但是我一开始没有定义@v_cmdstr2,就用了一个变量@v_cmdstr1,但是执行完之后发现数据库报错。之后对动态查询语句做了截断,动态部分用变量@v_cmdstr1 ,静态部分用了@v_cmdstr2,再执行就不报错了。但其实这时@v_cmdstr1 的长度仍然是>8000的,可见最大字符串可为2G并不是适用于所有场合。


沧海拾贝

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn