【问题标题】:SQL Server - Adding up variables combined with data-retrieval operationsSQL Server - 将变量与数据检索操作相结合
【发布时间】:2017-01-14 06:10:17
【问题描述】:

当我运行下面的代码时,我得到了这个错误:

为变量赋值的 SELECT 语句不能是 结合数据检索操作。

请看我下面的代码:

DECLARE @M1 float
DECLARE @M2 float
declare @M3 float
DECLARE @M4 float
DECLARE @M5 float
DECLARE @M6 float
DECLARE @M7 float
DECLARE @M8 float
DECLARE @M9 float
DECLARE @M10 float
DECLARE @M11 float
DECLARE @M12 float
declare @theSum float

set @M1 = 0
set @m2 = 1954286
set @M3 = 1954286
set @M4 = 0
set @M5 = 0
set @M6 = 0
set @M7 = 0
set @M8 = 0
set @M9 = -11725714
set @M10 = 1954286
set @M11 = 1954286
set @theSum = @M1+@M2+@M4+@M5+@M6+@M7+@M8+@M9+@M10+@M11+@M12

SELECT  @theSum,

        @M3   = case 
                --   when M3 = 0 then 0
                     when @M1+@M2+@M4+@M5+@M6+@M7+@M8+@M9+@M10+@M11+@M12 != 0 then @M3-@M2 -- mvc
                else
                    case when @M2 != 0 then @m3-@m2
                         when @M1 != 0 then @m3-@m1
                         when @M12 != 0 then @m3-@m12
                         when @M11 != 0 then @m3-@m11
                         when @M10 != 0 then @m3-@m10
                         when @M9 != 0 then @m3-@m9
                         when @M8 != 0 then @m3-@m8
                         when @M7 != 0 then @m3-@m7
                         when @M6 != 0 then @m3-@m6
                         when @M5 != 0 then @m3-@m5
                         when @M4 != 0 then @m3-@m4

                         else              @m3
                    end 
                end

没有必要解释我需要实现什么,我想要的只是一个示例,您可以将值分配给变量,然后在上面示例中的 case 语句中使用它们。任何例子都将不胜感激。

【问题讨论】:

标签: sql sql-server sql-server-2008 sql-server-2012


【解决方案1】:

我认为错误信息很清楚:查询要么分配变量或返回结果集,但不能同时分配两者。

这些不兼容:

SELECT  @theSum,
        @M3   = case . . .

也许你想要:

SELECT @M3 = case . . . ;

SELECT @theSum, @M3;

【讨论】:

  • 我明白了,谢谢。有什么方法可以重写这一行:when @M1+@M2+@M4+@M5+@M6+@M7+@M8+@M9+@M10+@M11+@M12 != 0 then @M3-@M2
  • @CM2K 。 . .只需使用when @theSum <> 0 then @M3 - @M2。你在select之前设置了@theSum,所以可以使用它。
猜你喜欢
  • 2010-09-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-08
  • 2011-11-05
  • 1970-01-01
  • 2012-05-23
相关资源
最近更新 更多