为什么SQL Server中的CTE在没有条件的情况下执行INNER JOIN?

时间:2014-01-31 15:35:44

标签: sql sql-server-2005 common-table-expression

我的表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

0 个答案:

没有答案