我有一个返回字符串的过程,如下所示
<USAGESTARTT=1387847400,USAGEENDT=1387849200,EVENTCOUNT=8,EVENTDURATION=247996,DISKSPACEUSED=0,BANDWIDTHOUT=0,BANDWIDTHCDN=0,HOURSUSED=0,AMOUNT=41332.66,RECYCLED_AMOUNT=0,NUM_RECYCLED_CDR=0,PROCESS_NAME=CP_RAX_RAT_SUSP,SERVICE_TYPE=CLOUD_BKUP>,<USAGESTARTT=0,USAGEENDT=1386032400,EVENTCOUNT=8,EVENTDURATION=74262,DISKSPACEUSED=0,BANDWIDTHOUT=0,BANDWIDTHCDN=0,HOURSUSED=0,AMOUNT=99.02,RECYCLED_AMOUNT=0,NUM_RECYCLED_CDR=0,PROCESS_NAME=CP_RAX_RAT_SUSP,SERVICE_TYPE=CLOUD_SRVR_UPTIME>,
这实际上是一组两行数据集相互连接在一起。单独看起来像
字符串1
<USAGESTARTT=1387847400,USAGEENDT=1387849200,EVENTCOUNT=8,EVENTDURATION=247996,DISKSPACEUSED=0,BANDWIDTHOUT=0,BANDWIDTHCDN=0,HOURSUSED=0,AMOUNT=41332.66,RECYCLED_AMOUNT=0,NUM_RECYCLED_CDR=0,PROCESS_NAME=CP_RAX_RAT_SUSP,SERVICE_TYPE=CLOUD_BKUP>,
String 2
<USAGESTARTT=0,USAGEENDT=1386032400,EVENTCOUNT=8,EVENTDURATION=74262,DISKSPACEUSED=0,BANDWIDTHOUT=0,BANDWIDTHCDN=0,HOURSUSED=0,AMOUNT=99.02,RECYCLED_AMOUNT=0,NUM_RECYCLED_CDR=0,PROCESS_NAME=CP_RAX_RAT_SUSP,SERVICE_TYPE=CLOUD_SRVR_UPTIME>,
我的要求是我想先将这个字符串拆分成不同的行,然后将每一行拆分成多列,其中'='前面的字符串是列名,'='后面的字符串是需要插入的值进入专栏。例如: - 在字符串'USAGESTARTT = 0'中,USAGESTARTT是列名,0是USAGESTARTT列中的值。此示例仅显示两行,但我的过程可以返回多个彼此连接的行。
您能否建议解决此要求?
答案 0 :(得分:1)
我用这个TVF分割字符串:
CREATE function dbo.split (@value varchar(8000),@delim varchar(8000))
returns table
as
return
(
select d.value,
d.orders,
ivalue = convert(int, case when isnumeric(d.value)=1 and d.value not like '%[^0-9 +-]%' and len(replace(replace(replace(d.value,' ',''),'-',''),'+',''))<=10 then case when convert(bigint,d.value) between -2147483648 and 2147483647 then d.value end end)
from
(
select
value= replace(substring(value,
idx,
case when cnt>=0 then cnt end
)
,char(1),'')
,orders=( datalength(left(value,idx-1))-datalength(replace(left(value,idx-1),@delim,''))
)/datalength(@delim)
from (
select number
,idx
,cnt = charindex(@delim,value, number + 1) - number - datalength(@delim)
,value
from
(
select number
,idx = number + datalength(@delim)
,value = (select @delim+char(1)+@value+char(1)+@delim)
from dbo.s_value
where number between 1 and datalength( (select @delim+char(1)+@value+char(1)+@delim) ) - datalength(@delim)
) t
where substring(t.value, number, datalength(@delim)) = @delim
) t
) d
)
GO
以这种方式使用:
select * from dbo.split(@YOUR_STRING,'>,<')
答案 1 :(得分:0)
如果您使用的是SQL Server,可以将字符串放在XML类型的变量中,然后解析此XML,请参阅Parse XML in SQL Server以获取示例。