如何在sql Trigger

时间:2017-07-03 09:26:08

标签: sql sql-server sql-server-2008 triggers

我创建了1个表,并且有1个列名为data。在数据领域,我得到的数据如下:

{"ip":"xxx.xx.xx.xxx","power":"7.15","sat":"10","status":"ok"}

{"ip":"xxx.xx.xx.xxx","power":"7.15","sat":"10","capacity":"20","status":"ok"}

{"ip":"xxx.xx.xx.xxx","power":"7.15","sat":"10","status":"ok"}

{"ip":"xxx.xx.xx.xxx","power":"7.15","sat":"10","capacity":"20","status":"ok"}

现在我创建了1个触发器,我将获取此数据。现在我想分割数据并希望得到capacity的值。

capacity位置并未修复,有时可能无法提供数据。

那么我怎样才能分裂并获得capacity的价值?我有SQL SERVER 2008。

3 个答案:

答案 0 :(得分:1)

假设你有Data这样的表

DECLARE @SampleData AS TABLE
(
    data varchar(200)
)

INSERT INTO @SampleData
(
    data
)
VALUES
('"ip":"xxx.xx.xx.xxx","power":"7.15","sat":"10","status":"ok"'),
('"ip":"xxx.xx.xx.xxx","power":"7.15","sat":"10","capacity":"20","status":"ok"'),
('"ip":"xxx.xx.xx.xxx","power":"7.15","sat":"10","status":"ok"'),
('"ip":"xxx.xx.xx.xxx","power":"7.15","sat":"10","capacity":"20","status":"ok"')

您可以使用字符串拆分功能和outer apply这样的

Select sd.data, replace(replace(c.value, '"', ''),'capacity:','') AS Capacity
FROM @SampleData sd
OUTER APPLY
(   SELECT *
    FROM [dbo].[SplitString](sd.data,',') c
    WHERE c.Value LIKE '%capacity%'
) c

返回

data                                                                Capacity
"ip":"xxx.xx.xx.xxx","power":"7.15","sat":"10","status":"ok"        NULL
"ip":"xxx.xx.xx.xxx","power":"7.15","sat":"10","capacity":"20","status":"ok"    20
"ip":"xxx.xx.xx.xxx","power":"7.15","sat":"10","status":"ok"         NULL
"ip":"xxx.xx.xx.xxx","power":"7.15","sat":"10","capacity":"20","status":"ok"    20

这是字符串拆分功能

CREATE FUNCTION [dbo].[SplitString] (@Text varchar(max),@Delimiter varchar(10))
Returns Table 
As
Return (  
   Select Pos = Row_Number() over (Order By (Select null))
        ,Value = LTrim(RTrim(B.i.value('(./text())[1]', 'varchar(max)')))
   From (Select x = Cast('<x>'+ Replace(@Text,@Delimiter,'</x><x>')+'</x>' as xml).query('.')) as A 
   Cross Apply x.nodes('x') AS B(i)
);

答案 1 :(得分:1)

如果您只需要容量值,那么当您只需从字符串中提取容量值时,就没有太多的分割数据了:

使用来自TriV答案的样本数据,您可以这样做:

;WITH CTE AS
(
    SELECT RIGHT(data, LEN(data) - PATINDEX('%,"capacity":%', data) - 11) As data
    FROM @SampleData  
    WHERE data LIKE '%,"capacity":%'
)

SELECT LEFT(data, PATINDEX('%","%', data)) As Capacity
FROM CTE

结果:

Capacity
"20"
"20"

See a live demo on rextester

答案 2 :(得分:-1)