2

I have the following CTE to update lTesterID column in table Employee to a valid ID randomly chosen from the table provider.

But I get this error

Cannot insert the value NULL into column 'lTesterID ', table 'Employee'; column does not allow nulls. UPDATE fails.

Even though there are no Null values as I'm excluding it in cteTable4.

Can someone point me in the right direction?

WITH    cteTable3
          AS ( SELECT   ROW_NUMBER() OVER ( ORDER BY NEWID() ) AS n ,
                        lTesterID
                        FROM     Employee
               WHERE lTesterID= 0 
             ),
        cteTable4
          AS ( SELECT   ROW_NUMBER() OVER ( ORDER BY NEWID() ) AS n ,
                        ISNULL(lTesterID,0) AS lTesterID
               FROM     Provider
               WHERE    Active = 'True'
                        AND lTesterID IS NOT NULL
             )
    UPDATE  cteTable3
    SET     lTesterID = ( SELECT  lTesterID
                            FROM    cteTable4
                            WHERE   cteTable3.n = cteTable4.n
                AND lTesterID IS NOT NULL
                          )
1
  • Thanks Mikael. It all makes sense now. Commented Mar 11, 2014 at 6:42

1 Answer 1

2

You are joining the CTE's on cteTable3.n = cteTable4.n in a correlated subquery. cteTable3.lTesterID will be updated with NULL where the subquery returns zero rows. That will happen if you have less rows returned from cteTable4 than you have from cteTable3.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.