I am trying to store XML data into a SQL Server 2008 R2 Express database, every xml file has different data. What is the easiest way to do this?
What are the best options please explain with example.
Ok, this is an example for storing the values of the xml into the table instead. I havent't tried this code but it should be working but at least it should clarify how to do as expected.
/* Imagine your xml looks something like this
<Content>
<Title>Text</Title>
<Value>15</Value>
</Content>
*/
CREATE TABLE [dbo].[MyXmlStorage]
(
[Id] [int] IDENTITY(1,1) NOT NULL,
[Title] [nvarchar](100) NOT NULL,
[Value] int NOT NULL,
CONSTRAINT [PK_MyXmlStorage]
PRIMARY KEY CLUSTERED ([Id] ASC)
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
CREATE PROCEDURE [dbo].[InsertXml]
(@filePathFull nvarchar(255))
AS
DECLARE @xmlAsString VARCHAR(MAX)
DECLARE @sql nvarchar(max)
DECLARE @xml XML
DECLARE @Rms_FileId nvarchar(50)
DECLARE @Rms_Id nvarchar(50)
DECLARE @Rms_Type nvarchar(50)
DECLARE @Rms_Timestamp nvarchar(50)
BEGIN
SET @sql = 'SELECT @xmlAsString = x.y FROM OPENROWSET( BULK ''' + RTRIM(@filePathFull) + ''', SINGLE_CLOB) x(y)'
exec sp_executesql @sql,N'@xmlAsString VARCHAR(MAX) OUTPUT',@xmlAsString OUTPUT
set @xml = CONVERT(XML,@xmlAsString)
/* Use xpath to query nodes for values inside the Content tag*/
INSERT INTO MyXmlStorage([Title],[Value])
SELECT
x.y.value('title[1]/text()[1]', 'nvarchar(100)') AS title,
x.y.value('value[1]/text()[1]', 'int') AS value
FROM @xml.nodes('//Content') AS x(y)
END
)