An alternative solution would be to create a secondary field in your target table that takes a string value. After filling the table with XML data, run the statement to update the whole field, setting it to NULL when the row field is empty.
For example, here is my XML string.
'<xml> <d MetricID="1" Days="15" Sort="1" /> <d MetricID="2" Days="45" Sort="2" /> <d MetricID="3" Days="29" Sort="3" /> <d MetricID="4" Days="119" Sort="4" /> <d MetricID="5" Days="59" Sort="5" /> <d MetricID="6" Days="179" Sort="6" /> <d MetricID="7" Days="0" Sort="7" /> <d MetricID="8" Days="" Sort="8" /> <d MetricID="9" Days="60" Sort="9" /> </xml>'
Nodes 7 and 8 have the corresponding values โโof days 0 and Blank. Zero must be saved, and empty must be saved as NULL. Here is my solution to achieve this.
DECLARE @idoc INT EXEC sp_xml_preparedocument @idoc OUTPUT, @xmlDeadline CREATE TABLE
Recall what happens above. The code captures the Days attribute twice. Put one in the INT column and one in the VARCHAR column. After executing the XML INSERT statement, run the UPDATE statement to convert the target INT field to NULL when it is associated with the VARCHAR column.
This approach can provide better performance than XQuery. I will leave it to someone else in this thread.
source share