2012-12-11 51 views
0

我是t-sql编程的新手。我有一个Java,Javascript和许多其他编程语言的背景。我试图设置@notes变量的值。我的代码如下。通过CASE语句设置值

基本上,如果@minBatch@maxBatch不为空,我想要做的是设置@notes变量。我添加了打印声明以确保@minBatch@maxBatch是我传入的值。

总之,以下代码有什么问题?

 
    set @notes = 
      case 
      when @minBatch != null and @maxBatch != null then 
       case 
        when @minBatch != @maxBatch then 
        'Start batch: ' + cast(@minBatch as varchar(8)) + ' End batch: ' + cast(@maxBatch as varchar(8)) 
        else 
        'Batch ' + cast(@minBatch as varchar(8)) 
       end 
      else 
       null 
      end 

回答

2

使用is null而不是=null

SELECT @notes = 
    CASE 
     WHEN (@minBatch + @maxBatch) is not null --Comment: if any null result is null 
       THEN 
       CASE @minBatch WHEN @maxBatch [email protected] or @max still can be null 
         THEN 'Batch ' + cast(ISNULL(@minBatch,0) as varchar(8)) 
         ELSE 'Start batch: ' + 
          cast(ISNULL(@minBatch,0) as varchar(8)) + ' End batch: ' + 
          cast(ISNULL(@maxBatch,0) as varchar(8)) 
       END 
     ELSE null 
    END 

编辑:简化的使用(@minBatch + @maxBatch) is not null

--Comment: if any null result is null 
+0

美丽。你做的编辑让它为我工作。谢谢! – acedanger