Sqlerver存储过程里定义了一个标量,在WHILE里循环赋值,不过循环结束后打印为空

declare  @strString VARCHAR(max)   = ''    -- 循环赋值内容的字符串

  declare @index int = 1  --起始下标

 declare @tableCount int = 0  --主表行数

 

 set   @tableCount = (select  count(1) from #TmpAll)

 

  WHILE(@index <= @tableCount)

begin

select @MaterialCode =  a.MaterialID,@SizeName = sz.SizeName,@StockID = InStockID, @CheckDate = InCheckDate  from #TmpAll  a 

inner join SD_Mat_Size sz on a.SizeID=sz.SizeID   

where id =  @index

  

   -- 7天

  set @strString = ''

    select  @seveDay = sum(qty) from #tableA_2  where MaterialCode  = '' + @MaterialCode +'' and SizeName  = '' + @SizeName +''   and  StockID =  '' + @StockID +''

  and CheckDate BETWEEN  CONVERT(varchar(100), @CheckDate, 20) and     DATEADD(dd,7,CONVERT(varchar(100),  @CheckDate, 20))  

 

    -- 14天

     select  @fourThen = sum(qty) from #tableA_2  where MaterialCode  = '' + @MaterialCode +'' and SizeName  = '' + @SizeName +''   and  StockID =  '' + @StockID +''

  and CheckDate BETWEEN  CONVERT(varchar(100), @CheckDate, 20) and     DATEADD(dd,14,CONVERT(varchar(100),  @CheckDate, 20)) 

      --21天

  select  @twentyOne = sum(qty) from #tableA_2  where MaterialCode  = '' + @MaterialCode +'' and SizeName  = '' + @SizeName +''   and  StockID =  '' + @StockID +''

  and CheckDate BETWEEN  CONVERT(varchar(100), @CheckDate, 20) and     DATEADD(dd,21,CONVERT(varchar(100),  @CheckDate, 20)) 

      --28天

    select  @twentyEight = sum(qty) from #tableA_2  where MaterialCode  = '' + @MaterialCode +'' and SizeName  = '' + @SizeName +''   and  StockID =  '' + @StockID +''

  and CheckDate BETWEEN  CONVERT(varchar(100), @CheckDate, 20) and     DATEADD(dd,28,CONVERT(varchar(100),  @CheckDate, 20)) 

 

   set @strString = @strString + '  update #TmpAll set '

if @seveDay > 0 

begin

   set @strString = @strString + '  count1 =   ' + CONVERT(varchar(100), @seveDay, 20)  +','

end 

if @fourThen > 0 

begin

set @strString = @strString + '  count2 =   ' + CONVERT(varchar(100), @fourThen, 20)+','

end

if @twentyOne > 0 

begin

set @strString = @strString + '  count3 =   ' +  CONVERT(varchar(100), @twentyOne, 20)+','

end

set @strString = @strString + '  count4 =   ' + CONVERT(varchar(100), @twentyEight, 20)

   

set @strString = @strString + '   where id =   ' + CONVERT(varchar(100), @index, 20) + ' ;'

 

  

 

set @index =  @index + 1 

end 

    print @strString -- 打印为空

SQL testAI01 发布于 2023-7-14 14:55
1min目标场景问卷 立即参与
回答问题
悬赏:0 F币 + 添加悬赏
提示:增加悬赏、完善问题、追问等操作,可使您的问题被置顶,并向所有关注者发送通知
共1回答
最佳回答
0
Z4u3z1Lv6专家互助
发布于2023-7-14 15:15

粗略来看 你的strString 循环拼接的  当传入变量是null的时候 拼接的结果就为空

只要while里面拼接的参数值出现一个null就全空了

image.png

  • 2关注人数
  • 151浏览人数
  • 最后回答于:2023-7-14 15:15
    请选择关闭问题的原因
    确定 取消
    返回顶部