Initially I have a column (partner_email) of type varchar. Now a recent change has come where it needs to be changed to be changed to the XML datatype but the existing rows needs to be converted into the new column.
Help needed
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Stepping through the scripts will help understand the problem:
Script 1
partner_email_tempdoes not exist in the Partnertable, add
partner_email_tempas an XML columnpartner_email_temptobe an XML-friendly string version of
partner_email. Then convert it to XML. Use REPLACE to convert all & to the encoded &partner_emailfrom Partnerpartner_email_temptopartner_emailAll of this works the first time. When you run the script a second time, SQL Server gets to Step 2 and executes the ALTER TABLE statement again. This is because the column
partner_email_tempdoes not exist (it was renamed in the first run to partner_email).Now in step 3, you are attempting to update the
partner_emailcolumn again. The problem is that this column is now an XML data type and your use ofREPLACEis illegal. So SQL Server throws an error.Script 2
partner_emailcolumn inPartner.
of the script), execute the code in the BEGIN and END
partner_email_tempdoes not exist, add thepartner_email_tempcolumn as an XMLpartner_email_tempto be an XML-friendly string version of
partner_emailand thenconvert it to XML. Use
REPLACEto convert all & to the encoded &partner_emailfrom Partnerpartner_email_temptopartner_emailThe problem in the second script is that you cannot use the
GOstatement in your BEGIN and END statement.According to BOL:
So in script 2, when SQL Server attempts to compile, it notices that the column
partner_email_tempdoesn’t exist. It works in the Script 1 because the sections are executed separately. And when the portion that referencespartner_email_tempis executed, the column does exist.So how do you fix it?
You can actually bypass all the dropping and renaming of columns if you simply update the data in the
partner_emailcolumn to the correct format and then convert the column to an XML data type. This can be achieved in one SQL batch statement, but you need to execute it as dynamic SQL so that SQL Server will only try to execute theREPLACEstatement when thepartner_email columnis a varchar data type: