Monday, April 2, 2012

How to update XML attribute, stored in SQL Table

Let say you have an XML stored in your Table.
You would like to update a particular attribute
using a stored procedure. To so the same follow below steps.

*******************************************************
Run below script in your SQL query analyzer
*******************************************************

--lets say I have Stored procedure as below.

Alter PROCEDURE updateFileTable
(
@file NVARCHAR(100),
@public NVARCHAR(100),
@fileTypeId NVARCHAR(100)
)
AS

-- Step 1 - Creating a Temporary table.
CREATE TABLE #FileTable
(
cFileName XML,
)
-- Step 2 - Inserting the test data give by you.

INSERT INTO #FileTable
([cFileName])
VALUES
(''+
''+
''+
'
')

----------------------------
PRINT 'Before Update'
SELECT * FROM #FileTable
----------------------------

--Step 3 - Updating the data.
-- here, in just tje below line the last 1 signifies that the while condition has returned true, and only then the update will take place

WHILE EXISTS (SELECT * FROM #FileTable WHERE cFileName.exist('/Files//File/@FileID[.=sql:variable("@file")]') = '1')
UPDATE #FileTable
SET cFileName.modify('replace value of (/Files//File/@FileID[.="1"])[1] with "10"')

----------------------------
PRINT 'After Update'
SELECT * FROM #FileTable
----------------------------

DROP table #FileTable

*******************************************************
Now EXECUTE the Stored PROCEDURE USING below STATEMENT.
*******************************************************

EXEC updateFileTable '1','false','9'

Tuesday, March 20, 2012

Linking the XSL Style Sheet to the XML Document



Using this approach, you do not need any code behind to have an
transformation for your only client side requirement.
Save following two files in your C:\SomeFolder

File1 - Home.xml

<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="UseMeToTransform.xsl"?>
<Root>
<Item>
<cat>1</cat>
<Name>Car</Name>
</Item>
<Item>
<cat>2</cat>
<Name>Bike</Name>
</Item>
<Item>
<cat>3</cat>
<Name>Boat</Name>
</Item>
</Root>

File2 - UseMeToTransform.xsl

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="Root">
<html>
<table border="1">
<tr>
<td>
<xsl:value-of select="'Category'"/>
</td>
<td>
<xsl:value-of select="'Name'"/>
</td>
</tr>
<xsl:for-each select="Item">
<tr>
<td>
<xsl:value-of select="cat"/>
</td>
<td>
<xsl:value-of select="Name"/>
</td>
</tr>
</xsl:for-each>
</table>
</html>
</xsl:template>
</xsl:stylesheet>

Now double click onthe Home.xml files you will get the desired output.
Where you can see that the date of Home.xml has been converted in to HTML contents.