Thursday, 2 August 2012

To Split the String Value


SET NOCOUNT ON;
GO

Declare @data varchar(100) = 'MDEB KLP 657 678989'
Declare @date varchar(100) = '2012-5-06'


DECLARE @T TABLE ([description] varchar(MAX));

INSERT INTO @T ([description]) VALUES (@data)

Insert into [TblEBMeterReading]
SELECT
 @date as Date,
 --Q.x.value('(/e/text())[1]', 'varchar(MAX)') [Category],
 Q.x.value('(/e/text())[2]', 'varchar(25)') CenterCode,
 Q.x.value('(/e/text())[3]', 'int') MeterNo,
 Q.x.value('(/e/text())[4]', 'int') MeterReading
FROM
 @T AS T
 CROSS APPLY
 (SELECT T.[description] AS [text()] FOR XML PATH('')) AS R(s)
 CROSS APPLY
 (SELECT CAST('<e>' + REPLACE(R.s, ' : ', '</e><e>') + '</e>' AS xml)) AS S(x)
 CROSS APPLY
 S.x.nodes('/e') AS N1(e)
 CROSS APPLY
 (SELECT CAST('<e>' + REPLACE(REPLACE(N1.e.value('text()[1]', 'varchar(MAX)'), ' ', '</e><e>'), ' ', '</e><e>') + '</e>' AS xml)) AS Q(x)
GO

No comments:

Post a Comment