TSQL更新查询意外行为

时间:2012-02-15 20:53:06

标签: tsql

我有一个嵌套的选择查询,返回适当的行数。该查询构建一个记录集并将其与表进行比较,并返回查询中不在表中的记录。

我将选择查询转换为更新查询。我试图用查询返回的行填充表。当我运行更新查询时,它返回零行进行更新。我不明白为什么因为select查询返回记录而我在更新查询中使用相同的代码。

由于

选择查询:(这将返回多条记录)

    Select *
From
(SELECT DISTINCT
 ProductClass,SalProductClass.[Description],B.Branch,B.BranchDesc,B.Salesperson,B.Name,
 CAST(0 AS FLOAT) AS Rate,'N' AS Split
FROM (SELECT SalBranch.Branch,SalBranch.[Description] AS BranchDesc,A.Salesperson,A.Name
      FROM (SELECT DISTINCT
             Salesperson,Name
            FROM SalSalesperson
            ) A
      CROSS JOIN SalBranch
      ) B
CROSS JOIN SalProductClass
) C
Left Outer Join RateComm On
RateComm.ProductClass = C.ProductClass and 
RateComm.Branch = C.Branch And RateComm.Salesperson = C.Salesperson
Where RateComm.ProductClass is Null

更新查询:(这是返回零记录)

UPDATE RateComm 
SET RateComm.ProductClass=C.ProductClass,RateComm.ProdClassDesc=C.ProdClassDesc,
RateComm.Branch=C.Branch,RateComm.BranchDesc=C.BranchDesc,RateComm.Salesperson=C.Salesperson,
RateComm.Name=C.Name,RateComm.Rate=C.Rate,RateComm.Split=C.Split
    FROM (SELECT DISTINCT
           ProductClass,SalProductClass.[Description] AS ProdClassDesc,B.Branch,B.BranchDesc,B.Salesperson,B.Name,
           CAST(0 AS FLOAT) AS Rate,'N' AS Split
          FROM (SELECT SalBranch.Branch,SalBranch.[Description] AS BranchDesc,A.Salesperson,A.Name
                FROM (SELECT DISTINCT
                       Salesperson,Name
                      FROM SalSalesperson
                      ) A
                CROSS JOIN SalBranch
                ) B
          CROSS JOIN SalProductClass
          ) C
    LEFT OUTER JOIN RateComm ON C.ProductClass=RateComm.ProductClass AND 
    C.Salesperson=RateComm.Salesperson AND C.Branch=RateComm.Branch
    WHERE RateComm.ProductClass IS NULL

1 个答案:

答案 0 :(得分:2)

很难更新不存在的内容。您是否尝试过INSERT查询?