我想以这种格式拆分字符串引用:
"date=10/10/2000|age=13^date=01/01/2001|age=12^date=02/02/2005|age=8"
. 实际上这个字符串只是一个示例,我的原始字符串非常大。我没有得到一点,如果我打破这个字符串比我必须制作多少个变量来捕获数据也是在拆分字符串之后我希望将其插入到包含日期和年龄列的数据表中?我使用什么概念?(我从网络服务中获取这个字符串)提前谢谢..
我想以这种格式拆分字符串引用:
"date=10/10/2000|age=13^date=01/01/2001|age=12^date=02/02/2005|age=8"
. 实际上这个字符串只是一个示例,我的原始字符串非常大。我没有得到一点,如果我打破这个字符串比我必须制作多少个变量来捕获数据也是在拆分字符串之后我希望将其插入到包含日期和年龄列的数据表中?我使用什么概念?(我从网络服务中获取这个字符串)提前谢谢..
一般来说,我建议编写一个 CLR 函数,它通过正则表达式或 SQL 表值函数拆分字符串,但在你的情况下,你可以尝试一些简单的事情,比如将你的字符串转换为 xml 并解析它:
declare @str nvarchar(max) = 'date=10/10/2000|age=13^date=01/01/2001|age=12^date=02/02/2005|age=8'
declare @data xml
select @str = replace(@str, '=', '="')
select @str = replace(@str, '|', '" ')
select @str = replace(@str, '^', '"/><row ')
select @str = '<row ' + @str + '"/>'
select @data = cast(@str as xml)
select
t.c.value('@date', 'nvarchar(max)') as [date],
t.c.value('@age', 'nvarchar(max)') as [age]
from @data.nodes('row') as t(c)
尝试这个:
Declare @stringToSplit varchar(max)='date=10/10/2000|age=13^date=01/01/2001|age=12^date=02/02/2005|age=8^date=10/10/2000|age=13^date=01/01/2001|age=12^date=02/02/2005|age=8^date=10/10/2000|age=13^date=01/01/2001|age=12^date=02/02/2005|age=8^date=10/10/2000|age=13^date=01/01/2001|age=12^date=02/02/2005|age=8'
DECLARE @YourTable table (RowID int, Layout varchar(max))
INSERT @YourTable VALUES (1,@stringToSplit)
;WITH SplitSting AS
(
SELECT
RowID,LEFT(Layout,CHARINDEX('^',Layout)-1) AS Part
,RIGHT(Layout,LEN(Layout)-CHARINDEX('^',Layout)) AS Remainder
FROM @YourTable
WHERE Layout IS NOT NULL AND CHARINDEX('^',Layout)>0
UNION ALL
SELECT
RowID,LEFT(Remainder,CHARINDEX('^',Remainder)-1)
,RIGHT(Remainder,LEN(Remainder)-CHARINDEX('^',Remainder))
FROM SplitSting
WHERE Remainder IS NOT NULL AND CHARINDEX('^',Remainder)>0
UNION ALL
SELECT
RowID,Remainder,null
FROM SplitSting
WHERE Remainder IS NOT NULL AND CHARINDEX('^',Remainder)=0
)
select SUBSTRING(part,CHARINDEX('=',part)+1,(CHARINDEX('|',part)-CHARINDEX('=',part))-1) as [Date],RIGHT(part,CHARINDEX('=',reverse(part))-1) as [Age] from SplitSting
DECLARE @s VARCHAR(300)
SET @s = 'RELGENINS|1121232243434|343434343434|343434-683211|34343434.00|CIT|22297568|NA|INR|ONDIRECT|NA|NA|NA|22-03-2014 10:43:20|0300|NA|NA|NA|NA|NA|NA|NA|NA|NA|Success|1790153891'
DECLARE @tmp TABLE( aDate varchar(50))
;WITH MyRows AS
(
SELECT LEFT(@s, CHARINDEX('|', @s) -1) AS MyRow, RIGHT(@s, LEN(@s) - CHARINDEX('|', @s)) AS Remainder
UNION ALL
SELECT LEFT(Remainder, CHARINDEX('|', Remainder) -1) AS MyRow, RIGHT(Remainder, LEN(Remainder) - CHARINDEX('|', Remainder)) AS Remainder
FROM MyRows
WHERE CHARINDEX('|', Remainder)>0
UNION ALL
SELECT Remainder AS MyRow, NULL AS Remainder
FROM MyRows
WHERE CHARINDEX('|', Remainder)=0
)
INSERT INTO @tmp (aDate)
SELECT SUBSTRING(MyRow, 0, 20) as date
FROM MyRows
SELECT *
FROM @tmp