user1212337
user1212337

Reputation: 11

TSQL Update Query behaving unexpectedly

I have a nested select query that is returning the proper amount of rows. The query builds a recordset and compares it to a table and returns the records in the query that are not in the table.

I converted the select query to an update query. I am trying to populate the table with the rows returned from the query. When I run the update query it is returning with zero rows to update. I dont understand why because the select query is returning record and I am using the same code in the update query.

Thanks

Select Query: (This is returning several records)

    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 Query: (This is returning zero records)

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

Upvotes: 1

Views: 74

Answers (1)

pete
pete

Reputation: 25091

It's difficult to update what doesn't exist. Have you tried an INSERT query instead?

Upvotes: 2

Related Questions