以下代码运行正常,但我觉得它太长了, 我想在“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
答案 0 :(得分: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
这实际上并没有真正缩短。但是有了几个找到匹配行的标准,我不确定你是否可以缩短它。
答案 1 :(得分: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