用if ....更新表

时间:2015-01-10 15:52:09

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

我的数据库中有这个表:

GroupStandings
+--------+----------+--------------+--------+
| TeamID | GoalsFor | GoalsAgainst | Points |
+--------+----------+--------------+--------+
|      1 |        0 |            0 |      0 |
|      2 |        0 |            0 |      0 |
|      3 |        0 |            0 |      0 |
|      4 |        0 |            0 |      0 |
+--------+----------+--------------+--------+

我想编写一个查询,根据我更新我的GoalsFor和GoalsAgainst更新积分。 澄清的一个非常糟糕的例子:

update GroupStandings
set GoalsFor = 3, GoalsAgainst = 1,
    if GoalsFor>GoalsAgainst set points = 3
    else if GoalsFor=GoalsAgainst set points =1
    else set points = 0
where TeamID = 1

2 个答案:

答案 0 :(得分:2)

不确定您的示例查询的工作版本是否是您尝试实现的所有内容,但如果是这样,您想要使用CASE

update GroupStandings
set GoalsFor = 3
  , GoalsAgainst = 1
  , points = CASE WHEN GoalsFor>GoalsAgainst THEN 3
                  WHEN GoalsFor=GoalsAgainst THEN 1
                  ELSE 0
             END
where TeamID = 1

<强>更新

根据要启动的所有值0,您可以将Points设为计算列:

ALTER TABLE YourTable DROP COLUMN Points;
GO
ALTER TABLE YourTable ADD Points AS (CASE WHEN GoalsFor>GoalsAgainst THEN 3
                                          WHEN GoalsFor=GoalsAgainst THEN 1
                                          ELSE 0
                                    END);

或者您可以运行2次更新:

update GroupStandings
set GoalsFor = 3
  , GoalsAgainst = 1
where TeamID = 1
GO
update GroupStandings
set points = CASE WHEN GoalsFor>GoalsAgainst THEN 3
                  WHEN GoalsFor=GoalsAgainst THEN 1
                  ELSE 0
             END
where TeamID = 1

或者您可以使用变量来存储更新值并在单次更新中使用它们:

DECLARE @GoalsFor INT = 3
       ,@GoalsAgainst INT = 1
update GroupStandings
set GoalsFor = @GoalsFor
  , GoalsAgainst = @GoalsAgainst
  , points = CASE WHEN @GoalsFor>@GoalsAgainst THEN 3
                  WHEN @GoalsFor=@GoalsAgainst THEN 1
                  ELSE 0
             END
where TeamID = 1

答案 1 :(得分:2)

检查此代码并希望这可以帮助您:

在此代码中,您可以在变量中设置GoalsFor和GoalsAgainst值,然后可以进行比较,以便针对每个teamid更新点数。

Declare @GoalsFor int 
Declare @GoalsAgainst int

Set @GoalsFor = 3
Set @GoalsAgainst = 1 

Update GroupStandings Set GoalsFor = @GoalsFor, GoalsAgainst = @GoalsAgainst, 
Points = Case When @GoalsFor > @GoalsAgainst then 3 
              When @GoalsFor = @GoalsAgainst then 1 
              else 0 end
Where TeamId = 1

select * from GroupStandings