網上有人問:html
declare @WH varchar(MAX)
set @WH='C1,C2,C3-C9,C20,C22,C30-C35'
想要循環截取出含有-的字符串 C3-C9,C30-C35,展開C3-C9,C30-C35,
將@WH替換爲 'C1,C2,C3,C4,C5,C6,C7,C8,C9,C20,C22,C30,C31,C32,C33,C34,C35'
Insus.NET也想練習一下。node
寫一個自定義函數來處理須要展開的字符串:ide
SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: Insus.NET -- Create date: 2019-05-27 -- Update date: 2019-05-27 -- Description: 填充中斷的字符串 -- ============================================= CREATE FUNCTION [dbo].[svf_FillConnectionString] ( @string NVARCHAR(MAX) ) RETURNS NVARCHAR(MAX) AS BEGIN DECLARE @rtv NVARCHAR(MAX) = N'' DECLARE @hyphen VARCHAR(1) = N'-' IF @string LIKE '%'+ @hyphen +'%' BEGIN DECLARE @hyphen_position INT = CHARINDEX(@hyphen, @string) DECLARE @Front NVARCHAR(40) = SUBSTRING(@string, 1, @hyphen_position - 1) DECLARE @Back NVARCHAR(40) = SUBSTRING(@string, @hyphen_position + 1, LEN(@string)- @hyphen_position) DECLARE @f INT = CAST(SUBSTRING(@Front, 2, LEN(@Front) - 1) AS INT) DECLARE @b INT = CAST(SUBSTRING(@Back, 2, LEN(@Back) - 1) AS INT) WHILE @f <= @b BEGIN SET @rtv = @rtv + N',' + N'C' + CAST(@f AS NVARCHAR(MAX)) SET @f = @f + 1 END END RETURN CASE WHEN LEN(ISNULL(@rtv,N'')) = 0 THEN @string ELSE STUFF(@rtv,1,1,N'') END END
另外一個自定義函數:函數
把字符串轉換爲表:post
SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: Insus.NET -- Create date: 2019-05-27 -- Update date: 2019-05-27 -- Description: 拆分字符串轉爲表 -- ============================================= CREATE FUNCTION [dbo].[tvf_ConvertStringToTable] ( @OriginalString NVARCHAR(MAX), @Delimiter CHAR(1) ) RETURNS @Result TABLE ([value] NVARCHAR(MAX)) AS BEGIN DECLARE @xml XML = CAST('<insus>' + REPLACE(@OriginalString,@Delimiter,'</insus><insus>') + '</insus>' AS XML) INSERT INTO @Result([value]) SELECT n.value('.','NVARCHAR(MAX)') AS w FROM @xml.nodes('/insus') AS E(n) RETURN END GO
如今試使用上面2個函數,看看結果如何?url
DECLARE @WH VARCHAR(MAX) SET @WH='C1,C2,C3-C9,C20,C22,C30-C35' ;WITH HW AS ( SELECT [value] FROM [dbo].[tvf_ConvertStringToTable](@WH,',') ) SELECT [value],[dbo].[svf_FillConnectionString]([value]) as [str] FROM HW
差很少接近要求了,如今只要把[str]這列的數據鏈接起來就OK了。spa
如何鏈接,參考這篇《列值轉換爲逗號分隔字符串》http://www.javashuo.com/article/p-ozhapbwe-kk.htmlcode
DECLARE @ok_string NVARCHAR(MAX) DECLARE @WH VARCHAR(MAX) SET @WH='C1,C2,C3-C9,C20,C22,C30-C35' ;WITH HW AS ( SELECT [value] FROM [dbo].[tvf_ConvertStringToTable](@WH,',') ) --SELECT [value],[dbo].[svf_FillConnectionString]([value]) as [str] FROM HW SELECT @ok_string = ISNULL(@ok_string + ',', '') + [dbo].[svf_FillConnectionString]([value]) FROM HW SELECT @ok_string
大功告成!xml