CASE语句更新查询错误

时间:2016-01-03 06:23:51

标签: sql sql-server-2008 case

我正在使用CASE语句来更新一些表数据,但它在WHEN和THEN Condition.any主体可以告诉我们错误的错误错误。这是我的代码,

UPDATE TBL_AMOUNT_SETTING 
SET CALCULATED_AMOUNT =
        CASE
           WHEN EXISTS(SELECT COUNT(*) 
                       FROM TBL_GAME_PRICE_BY_DATE 
                       WHERE GAMEPRICE_DATE = CONVERT(DATE,GETDATE())) 
             THEN 
                (SELECT GAMEPRICE 
                 FROM TBL_GAME_PRICE_BY_DATE 
                 WHERE GAMEID = 10 
                   AND GAMEPRICE_DATE = CONVERT(DATE,GETDATE()))
           ELSE NULL
        END
 WHERE REF_GAME_ID = 10         

3 个答案:

答案 0 :(得分:0)

您的SQL错误,您错过了案例关键字

模板如下:

select case 
  when exists (
  ...
  ) 
  then ...
  else ...
  end
  where ...

更新相同:

  update tbl set field =
  case 
  when exists (
  ...
  ) 
  then ...
  else ...
  end
  where ...

答案 1 :(得分:0)

您的问题的原始问题是Case查询中缺少update个关键字。

我认为更好的做法是将更新语句的过程分开。由于您的subquery都不是correlated,因此您可以尝试使用

这是可读然后你在做什么

DECLARE @gameprice NUMERIC(22, 6) 

IF EXISTS(SELECT Count(*) 
          FROM   tbl_game_price_by_date 
          WHERE  gameprice_date = CONVERT(DATE, Getdate())) 
  SELECT @gameprice = gameprice 
  FROM   tbl_game_price_by_date 
  WHERE  gameid = 10 
         AND gameprice_date = CONVERT(DATE, Getdate()) 

UPDATE tbl_amount_setting 
SET    calculated_amount = @gameprice 
WHERE  ref_game_id = 10 

答案 2 :(得分:0)

试试..

UPDATE tbl_amount_setting 
SET    calculated_amount = ( CASE 
                               WHEN EXISTS(SELECT Count(*) 
                                           FROM   tbl_game_price_by_date 
                                           WHERE  gameprice_date = 
                                                  CONVERT(DATE, Getdate())) THEN 
                               (SELECT Max(gameprice) 
                                FROM 
                             tbl_game_price_by_date 
                               WHERE 
                             gameid = tbl_amount_setting.ref_game_id 
                             AND gameprice_date = CONVERT(DATE, Getdate())) 
                               ELSE NULL 
                             END ) 
WHERE  ref_game_id = 10