数据收集器将时间序列数据发送到sql server 2008.为了使数据表更简洁,时间序列以envelop []的形式发送。 这是存储在sql server
中的数据
我的工作是在每一行中对READINGS列求和,例如在上表中得到(0,18,22,28,...)之和。如果有任何函数在sql server中展开{envelope:[{0,0],...}等数据?
答案 0 :(得分:0)
借助解析器UDF
Declare @YourTable table (Readings varchar(50))
Insert Into @YourTable values
('{envelope:[{0:0},{1:18},{2:22},{3:28},]}'),
('{envelope:[{0:0},{1:12},{2:17},{3:24},]}')
Select A.*
,B.Total
From @YourTable A
Cross Apply (Select Total = sum(cast(Substring(Key_Value,1,charindex('}',Key_Value)-1) as int)) from [dbo].[udf-Str-Parse](Readings,':') where ISNUMERIC(left(Key_Value,1))=1 ) B
返回
Readings Total
{envelope:[{0:0},{1:18},{2:22},{3:28},]} 68
{envelope:[{0:0},{1:12},{2:17},{3:24},]} 53
UDF(如果需要)
CREATE FUNCTION [dbo].[udf-Str-Parse] (@String varchar(max),@Delimeter varchar(10))
--Usage: Select * from [dbo].[udf-Str-Parse]('Dog,Cat,House,Car',',')
-- Select * from [dbo].[udf-Str-Parse]('John Cappelletti was here',' ')
Returns @ReturnTable Table (Key_PS int IDENTITY(1,1), Key_Value varchar(max))
As
Begin
Declare @XML xml;Set @XML = Cast('<x>' + Replace(@String,@Delimeter,'</x><x>')+'</x>' as XML)
Insert Into @ReturnTable Select ltrim(rtrim(String.value('.', 'varchar(max)'))) FROM @XML.nodes('x') as T(String)
Return
End