SQL中的子查询

时间:2014-07-05 07:00:07

标签: sql sql-server

我正试图想办法对数据库进行更新,但我一直在失败。我真的想不出别的东西。

  IF @EventID = 9
   BEGIN
   declare @HwanLevel int;
   UPDATE SRO_VT_SHARD.._Char set HwanLevel = 1 WHERE CharID in (SELECT TOP(1) EXP,LEVEL,CONTRIBUTION FROM SRO_VT_SHARD.._CharTrijob WHERE JobType = 1 AND CharID = @CharID)
   UPDATE SRO_VT_SHARD.._Char set HwanLevel = 2 WHERE CharID in (SELECT TOP(1) EXP,LEVEL,CONTRIBUTION FROM SRO_VT_SHARD.._CharTrijob WHERE JobType = 2 AND CharID = @CharID)
   UPDATE SRO_VT_SHARD.._Char set HwanLevel = 3 WHERE CharID in (SELECT TOP(1) EXP,LEVEL,CONTRIBUTION FROM SRO_VT_SHARD.._CharTrijob WHERE JobType = 3 AND CharID = @CharID)
   END
OHH,当我试图使用它时,我一直在努力; “当EXISTS没有引入子查询时,只能在选择列表中指定一个表达式。” 我尝试过加入等等和案例,但没有真正解决。我要做的是:

SELECT Top(1) EXP,Contribution,Level
THEN check if Jobtype = 1 then set HwanLevel to 1
if jobtype = 2 then set hwanlevel to 2
etc until 3

2 个答案:

答案 0 :(得分:1)

您返回的子查询声明了太多字段。只返回一个字段。所以它应该看起来:

SELECT CharID 
FROM SRO_VT_SHARD.._CharTrijob 
WHERE JobType = 1 AND CharID = @CharID

答案 1 :(得分:0)

您的top(1)只会响应查询中的ORDER BY子句。最好按照以下方式做点什么:

UPDATE SRO_VT_SHARD.._Char SET HwanLevel = Jobtype WHERE Jobtype = (select top(1)
Jobtype FROM SRO_VT_SHARD.._CharTrijob ORDER BY EXP,LEVEL,CONTRIBUTION)

当然它取决于ORDER BY中列的顺序,如果给定的序列产生顶级玩家那么好,否则你可以在ORDER BY中重新排序,即:

...ORDER BY CONTRIBUTION,EXP,LEVEL

如何使用变量,根据TOP 1 SELECT给出的Jobtype设置变量,然后从变量更新另一个表:

DECLARE @HWANLEVEL INT
SET @HWANLEVEL = (SELECT TOP 1 Jobtype FROM SRO_VT_SHARD.._CharTrijob 
                  ORDER BY EXP,LEVEL,CONTRIBUTION)
UPDATE SRO_VT_SHARD.._Char SET HwanLevel = @HWANLEVEL