zaagan
8/21/2019 - 4:40 PM

MS SQL Xml Check For Existance

MS SQL Xml Check For Existance

DECLARE @XML XML = '
<Y>
    <f>A</f>
    <r>B</r>
</Y>
<Y>
    <f>p</f>
    <r>q</r>
</Y>
<Y>
    <f>a</f>
    <r>b</r>
</Y>';

IF ( @XML IS NOT NULL
     AND @XML.exist('/Y') = 1 )
  BEGIN
      INSERT INTO [dbo].[Your-Table]
                  (Col1,
                   Col2,
                   Col3)
      SELECT 'Keyword',
             ( N.value('(f)[1]', 'nvarchar(100)') ),
             Lower(N.value('(r)[1]', 'nvarchar(100)'))
      FROM   @XML.nodes('Y') AS T ( N );
  END;

--- [XML DATA OUTPUT ]
-- Col1     | Col2 | Col3
---------------------------
--  Keyword    	A     	b
--  Keyword     p     	q
--  Keyword     a     	b