2014-12-02 58 views
3

一個字符串我在SQL字符串存儲在Varchar(MAX)@result變量是這樣的:如何扭轉在SQL Server

Attributes >> Items >> Category >> Package 

我怎樣才能得到這個反不影響存儲過程的性能。我想打破>>的基礎上的字符串。

Package >> Category >> Items >> Attributes 
+1

有沒有在字符串中最四種元素? – 2014-12-02 13:05:42

回答

3

如果字符串中最多四個項目並沒有包含句號,那麼你可以使用PARSENAME()

select (parsename(replace(@result, ' >> ', '.'), 1) + ' >> ' + 
     parsename(replace(@result, ' >> ', '.'), 2) + ' >> ' + 
     parsename(replace(@result, ' >> ', '.'), 3) + ' >> ' + 
     parsename(replace(@result, ' >> ', '.'), 4) 
     ) 

另一種選擇是拆分字符串並重構它。

+0

感謝您的回答。這是否會影響性能? – 2014-12-02 13:11:59

+1

無論何時您向程序添加任何類型的代碼,都會影響性能。該解決方案速度非常快,因此影響應該很小,甚至不可能引人注意。 – 2014-12-02 14:32:17

-3

如果您正在運行SQL Server 2008或更新,請嘗試:

Select Reverse(@result) 
+0

程序包<<類別<<項目<<屬性。這是輸出嗎? – knkarthick24 2014-12-02 13:18:24

+2

egakcaP >> yrogetaC >> smetI >> setubirttA – 2014-12-02 13:18:46

+0

他說這個字符串存儲在他的變量中。如果他希望字符串反轉,那麼最簡單的方法就是使用系統函數REVERSE(string_expression) – 2014-12-02 13:46:13

1

打破串入使用的分隔符>>的分配ROW_NUMBER每一行的不同部分。

然後Convert the rows into single string>>劃分順序desc。

,如果你有超過4個元素

這應該工作
DECLARE @output VARCHAR(5000)='', 
     @String VARCHAR(5000)='Attributes >> Items >> Category >> Package' 

SELECT @output += splt_data + ' >> ' 
FROM (SELECT Row_number() 
       OVER(
        ORDER BY (SELECT NULL))      rn, 
       Rtrim(Ltrim(Split.bb.value('.', 'VARCHAR(100)'))) splt_data 
     FROM (SELECT Cast ('<M>' + Replace(@String, '>>', '</M><M>') 
          + '</M>' AS XML) AS Data) AS A 
       CROSS APPLY Data.nodes ('/M') AS Split(bb)) ou 
ORDER BY rn DESC 

OUTPUT:

SELECT LEFT(@output, Len(@output) - 3) --Package >> Category >> Items >> Attributes