Monday, 17 February 2014

Creating XML Data from Table

Today I need to create a xml field from a table. To show you how it works I just created a small 3 row example table.
Lets have a look at the Script:
First of all I created a table with 3 columns (ItemNo, Item_Name, Item_Price) and inserted 3 example rows.
After that I created the XML Table with columns (ID, Article)
A small while loop inserted the XML into the table.
In the End you will see the 3 items as XML and one Testitem as XML Select in Columns.

Copyable Version:
-- Create Source Table
CREATE TABLE [dbo].[article](
        [ItemNo] [bigint] NOT NULL,
        [Item_Name] [nvarchar](250) NOT NULL,
        [Item_Price] [money] NOT NULL
) ON [PRIMARY]
go
INSERT INTO [article]
Select 1, 'Testitem 1', 2.00
UNION ALL
Select 2, 'Testitem 2', 3.99
UNION ALL
Select 3, 'Testitem 3', 5.99
-- XML Table
CREATE TABLE [dbo].[Article_XML](
        [ID] [INT] PRIMARY KEY,
        Article XML
)  ON [PRIMARY]
GO
-- Insert into XML
DECLARE @counter INT = 1
DECLARE @row VARCHAR(MAX)
WHILE @counter <= 3
    BEGIN
        SET @row = (
                SELECT    ItemNo,
                        Item_Name,
                        Item_Price
                FROM article
                WHERE ItemNo = @counter
                FOR XML PATH ('Article')
                )
        INSERT Article_XML Values (@counter, @row)
        SET @counter += 1
    END
GO
-- Select all Fields
Select * from Article_XML
GO
-- Select XML Path
SELECT    Article.value('(/Article/ItemNo)[1]','varchar(50)') AS Artno,
        Article.value('(/Article/Item_Name)[1]','varchar(50)') AS item_name,
        Article.value('(/Article/Item_Price)[1]','money') AS price
From Article_XML
Where Article.exist('/Article[ItemNo=1]') = 1

No comments:

Post a Comment