Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Building UPDATE dynamically
Message
 
General information
Forum:
Microsoft SQL Server
Category:
Stored procedures, Triggers, UDFs
Environment versions
SQL Server:
SQL Server 2012
Application:
Web
Miscellaneous
Thread ID:
01596792
Message ID:
01596794
Views:
37
>>I am trying to build a dynamic UPDATE statement in a SQL Server Stored Procedure.
>>
>>I pass to the SQL Stored procedure an XML string (@XmlDocWo) that has field name/value pairs. Then I extract a value for a field from the XML as following:
>>
>>
>>SELECT @Fld1Value = [Fld FldName].value('.','char(10)') FROM @XmlDocWo.nodes('/TABLE_NAME/Fld') Fld([Fld FldName]) 
>>	 WHERE [Fld FldName].value('@name','varchar(20)') = 'FLD1NAME'
>>
>>SELECT @ Fld2Value = [Fld FldName].value('.','char(10)') FROM @XmlDocWo.nodes('/TABLE_NAME/Fld') Fld([Fld FldName]) 
>>	 WHERE [Fld FldName].value('@name','varchar(20)') = 'FLD2NAME'
>>
>>
>>Then the Update command would be as follows:
>>
>>
>>UPDATE MyTable SET FLD1NAME = @Fld1Value, FLD2NAME = @Fld2Value where PK_FLD = @PkFldValue
>>
>>
>>The above expression would have more than 2 fields, of course. And I am looking for the way to eliminate one or some fields if they are not included in XML. For example, if XML string does not have value for FLD2NAME the UPDATE expression would be:
>>
>>
>>UPDATE MyTable SET FLD1NAME = @Fld1Value where PK_FLD = @PkFldValue
>>
>>
>>How would you suggest I go about it?
>
>By default all declared variables will be NULL. Assuming you will not be having NULL values in your XML file you can do
>
>update myTable SET Fld1Name = COALESCE(@Fld1Value, Fld1Name), etc.

I didn't know that I can skip declaring a variable. I thought that I always have to do
declare @MyVarName INT before using it.

I have never used COALESCE() either. The approach you describe should work. I will test it.
Thank you.
"The creative process is nothing but a series of crises." Isaac Bashevis Singer
"My experience is that as soon as people are old enough to know better, they don't know anything at all." Oscar Wilde
"If a nation values anything more than freedom, it will lose its freedom; and the irony of it is that if it is comfort or money that it values more, it will lose that too." W.Somerset Maugham
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform