2

下面的代码运行良好,但我觉得它太长了,我想在删除它之前将字段“MealNo”中的值“1”删除到具有字段 MealNo=2 的行中

下面的代码完成了这项工作,但我看到它很长,有什么办法可以缩短它吗?特别是在“哪里”之后

 if ((SELECT MealNo FROM [Temp_Food_TBL] WHERE [AutoNo] = @AutoNo) = 1)
    BEGIN 
        Update [Temp_Food_TBL]
        SET
         MealNo = 1
         Where
         MealNo = 2
         AND
         PersonID = (SELECT PersonID FROM [Temp_Food_TBL] WHERE [AutoNo] = @AutoNo)
         AND
         MealTime = (SELECT MealTime FROM [Temp_Food_TBL] WHERE [AutoNo] = @AutoNo)
         AND
         MealDate = (SELECT MealDate FROM [Temp_Food_TBL] WHERE [AutoNo] = @AutoNo)  
    END

 DELETE FROM [Temp_Food_TBL]
   WHERE 
 [AutoNo] = @AutoNo
4

2 回答 2

2

您可以尝试自联接而不是使用WHERE语句。

if ((SELECT MealNo FROM [Temp_Food_TBL] WHERE [AutoNo] = @AutoNo) = 1)
    BEGIN 
        UPDATE t1
        SET t1.MealNo = 1
        FROM [Temp_Food_TBL] AS t1
        INNER JOIN [Temp_Food_TBL] AS t2
          ON t1.PersonID = t2.PersonID
            AND t1.MealTime = t2.MealTime
            AND t1.MealDate = t2.MealDate
            AND t1.MealNo = 2 
        WHERE t2.AutoNo = @AutoNo 
    END 

   DELETE FROM [Temp_Food_TBL]
   WHERE [AutoNo] = @AutoNo

这并没有真正缩短。但是有几个标准可以找到匹配的行,我不确定你能不能把它缩短那么多。

于 2013-04-02T13:12:53.597 回答
1
;WITH DATA AS
(
      SELECT
            Temp_Food_TBL.*
      FROM
            Temp_Food_TBL
            INNER JOIN Temp_Food_TBL AS Match
                  ON Temp_Food_TBL.PersonID = Match.PersonID
                  AND Temp_Food_TBL.MealTime = Match.MealTime
                  AND Temp_Food_TBL.MealDate = Match.MealDate
                  AND Match.AutoNo = @AutoNo
                  AND Match.MealNo = 1
)
UPDATE DATA SET MealNo = 2

DELETE FROM Temp_Food_TBL WHERE AutoNo = @AutoNo
于 2013-04-02T13:16:40.647 回答