2016-03-14 21 views
4

我有一個要求是採用管道分隔的鍵 - 值對的字符串並將數據轉換爲列。動態識別字符串中鍵值對的數量

我有一個可以使用的工作方法,但是這裏假設傳入的數據在每次傳遞時都會被構造成相同的,並且如果添加了一個新的鍵值對並且我希望將來可以證明它越多越好。

這裏是DDL和樣本數據以及我迄今爲止工作的解決方案。

DDL:

CREATE TABLE #pipers (team_id nvarchar(50), piped_string nvarchar(250)) 

樣本數據:

INSERT INTO #pipers (team_id, piped_string) VALUES 
    (newid(), 'team_name:Brighton|stadium:American Express Community Stadium|max_attendance:30750') 
    ,(newid(), 'team_name:Middlesbrough|stadium:Riverside|max_attendance:34742') 
    ,(newid(), 'team_name:Derby|stadium:Pride Park Stadium|max_attendance:33597') 

當前的嘗試:

;WITH xmldata (team_id, piped_string, xml_string) 
    AS 
    (
    SELECT team_id 
     ,piped_string 
     ,CAST('<teaminfo>'+'<team>'+REPLACE(piped_string,'|','</team><team>')+'</team>'+'</teaminfo>' AS XML) 
    FROM #pipers 
    ) 

    SELECT team_id, 
     piped_string, 
     team_name = x.xml_string.value('(/teaminfo/team)[1]','nvarchar(150)'), 
     stadium = x.xml_string.value('(/teaminfo/team)[2]','nvarchar(150)'), 
     max_attendance = x.xml_string.value('(/teaminfo/team)[3]','nvarchar(150)') 
    FROM xmldata x 

我的問題是:我將如何去動態地識別內對數傳入的字符串並將其應用於XML邏輯?

+0

隨着2016版有加'+ 1'因爲你是不計算分隔符而是分離式項string_split – Paparazzi

回答

4

如果你只是想知道計數不喜歡這樣寫道:

DECLARE @str VARCHAR(MAX)='team_name:Brighton|stadium:American Express Community Stadium|max_attendance:30750'; 
SELECT LEN(@str)-LEN(REPLACE(@str,'|','')) + 1; 
+0

.. – Shnugo

+0

很好,謝謝。我可以解決這個問題,並解決其餘問題。 – BBassic

+0

爲了處理空字符串,可能值得在Len(@Str)= 0和0 else ... end'的情況下進行包裝。這可以很容易地擴展到處理NULL輸入。 – HABO