Saturday, March 5, 2011

CRUD using XML and XQuery

we have a table TestA with 2 columns (ID,Name) and ID is an identity column.
--INSERT----------------------------------------------

Declare @myXML XML

SET @myXML = N'
<rows>
<row  Name="33333" />
<row  Name="444444"  />
<row  Name="555555" />
</rows>'

DECLARE @NewIdTable TABLE (ID INT)

INSERT INTO TestA ([Name])
OUTPUT INSERTED.ID  INTO @NewIdTable  
SELECT T.Item.value('@Name','varchar(20)') AS Name
FROM @MyXML.nodes('/rows[1]/row') AS T(Item)

--UPDATE------------------------------------------------

Declare @myXML XML

SET @myXML = N'
<rows>
<row ID="3" Name="33333" />
<row ID="4" Name="444444"  />
<row ID="5" Name="555555" />
</rows>'

UPDATE TestA
SET [Name] = b.[Name]
FROM TestA a INNER JOIN 
  (SELECT T.Item.value('@ID','varchar(20)') AS ID,
        T.Item.value('@Name','varchar(20)') AS Name
   FROM @MyXML.nodes('/rows[1]/row') AS T(Item)) AS b
ON a.ID = b.ID

--DELETE---------------------------------------------

Declare @myXML XML

SET @myXML = N'
<rows>
<row ID="3" Name="33333" />
<row ID="4" Name="444444"  />
<row ID="5" Name="555555" />
</rows>'

DELETE A
FROM TestA A INNER JOIN 
 (SELECT T.Item.value('@ID','varchar(20)') AS ID,
         T.Item.value('@Name','varchar(20)') AS Name
  FROM @MyXML.nodes('/rows[1]/row') AS T(Item)) AS B
ON A.ID = B.ID

0 comments:

Post a Comment