我的表mse
包含所有行StatusId = 1
。但在查询中,无论列StatusId
的值如何,都会执行INNER JOINED VIEW。怎么预防呢?
WITH cte201401291517 AS
(
SELECT
'QuantityOutPerShift' = SUM([vsqo].[QuantityOutPerShift])
, [mse].[ShiftGroup]
, [mse].[Station]
, [vsqo].[Shift]
FROM
[dbo].[mse] AS mse
INNER JOIN
[dbo].[vmsqo] AS vsqo ON [mse].[Station] = [vsqo].[FromStation]
AND ( [mse].[ShiftGroup] = [vsqo].[ShiftGroup]
OR [mse].[ShiftGroup] = 'ALL') -- order is important!
WHERE
[mse].[StatusId] = 3
GROUP BY
[mse].[ShiftGroup]
, [mse].[Station]
, [vsqo].[Shift])
UPDATE
[dbo].[mse]
SET
[dbo].[mse].[QuantityOutPerShift] = [cte].[QuantityOutPerShift]
, [dbo].[mse].[ShiftCurrent] = [cte].[Shift]
--OUTPUT INSERTED.*
FROM
cte201401291517 AS cte
WHERE
[dbo].[mse].[Station] = [cte].[Station]
AND ( [dbo].[mse].[ShiftGroup] = [cte].[ShiftGroup]
OR [dbo].[mse].[ShiftGroup] = 'ALL' ) -- order is important!
AND [dbo].[mse].[StatusId] = 3;
如果没有CTE,我无法做到这一点,因为我正在使用SUM更新表,而不能在UPDATE
语句中使用。
我正在使用SQL Server 2005