I have a stored proc that inserts XML into an underlying table. Unfortunately the XML passed in as a Sql XML type sometimes has particular elements missing. This makes the INSERT statement insert XML node values into the wrong columns.
My T-SQL looks something like this:
ALTER PROCEDURE [dbo].[up_Test_Insert]
@xmlData XML
AS
BEGIN
INSERT INTO
TestTable
(
ColumnA,
ColumnB,
ColumnC
)
SELECT
Tbl.Col.value(ColumnA[1]', 'INT'),
Tbl.Col.value('ColumnB[1]', 'INT'),
Tbl.Col.value('ColumnC[1]', 'INT')
FROM
@xmlData.nodes('DocumentElement/DataTable') Tbl(Col)
Sometimes ColumnB element may be missing in the XML structure. This results in the ColumnC node value being inserted into the ColumnB table column.
Is there a way to make the “value” operator return null on missing elements?
You have probably simplified your sample a bit too much. What you have here works as expected and will not insert ColumnC values to table ColumnA and missing ColumnB tags will give you a null value.
Try this:
Result: