0
A
回答
1
首先我們分裂的字符串,並創建R1和R2,然後我們採用一個特設理貨表以填補這一空白
Declare @YourTable table (ID int,RangeString varchar(max))
Insert Into @YourTable values
(1,'1-5,6,7'),
(2,'25000-25010,10-15')
Select A.ID
,C.N
From @YourTable A
Cross Apply (
Select R1=cast(left(RetVal,charindex('-',RetVal+'-')-1) as int)
,R2=cast(case when charindex('-',RetVal)=0 then left(RetVal,charindex('-',RetVal+'-')-1) else replace(RetVal,left(RetVal,charindex('-',RetVal+'-')),'') end as int)
From (
Select RetSeq = Row_Number() over (Order By (Select null))
,RetVal = LTrim(RTrim(B.i.value('(./text())[1]', 'varchar(max)')))
From (Select x = Cast('<x>' + replace((Select replace(RangeString,',','§§Split§§') as [*] For XML Path('')),'§§Split§§','</x><x>')+'</x>' as xml).query('.')) as X
Cross Apply x.nodes('x') AS B(i)
) P
) B
Cross Apply (
Select Top (B.R2-B.R1+1) N=Row_Number() Over (Order By (Select null))+B.R1-1 From master..spt_values N1,master..spt_values N2
) C
返回
ID N
1 1
1 2
1 3
1 4
1 5
1 6
1 7
2 25000
2 25001
2 25002
2 25003
2 25004
2 25005
2 25006
2 25007
2 25008
2 25009
2 25010
2 10
2 11
2 12
2 13
2 14
2 15
編輯 - 使用UDF的清潔版
Select A.ID
,D.N
From @YourTable A
Cross Apply [dbo].[udf-Str-Parse](A.RangeString,',') B
Cross Apply (
Select R1=min(cast(RetVal as int))
,R2=max(cast(RetVal as int))
From [dbo].[udf-Str-Parse](B.RetVal,'-')
) C
Cross Apply (
Select Top (C.R2-C.R1+1) N=Row_Number() Over (Order By (Select null))+C.R1-1
From master..spt_values N1,master..spt_values N2
) D
的UDF如果有興趣
CREATE FUNCTION [dbo].[udf-Str-Parse] (@String varchar(max),@Delimiter varchar(10))
Returns Table
As
Return (
Select RetSeq = Row_Number() over (Order By (Select null))
,RetVal = LTrim(RTrim(B.i.value('(./text())[1]', 'varchar(max)')))
From (Select x = Cast('<x>' + replace((Select replace(@String,@Delimiter,'§§Split§§') as [*] For XML Path('')),'§§Split§§','</x><x>')+'</x>' as xml).query('.')) as A
Cross Apply x.nodes('x') AS B(i)
);
--Thanks Shnugo for making this XML safe
--Select * from [dbo].[udf-Str-Parse]('Dog,Cat,House,Car',',')
--Select * from [dbo].[udf-Str-Parse]('John Cappelletti was here',' ')
--Select * from [dbo].[udf-Str-Parse]('this,is,<test>,for,< & >',',')
--Performance On a 5,000 random sample -8K 77.8ms, -1M 79ms (+1.16), -- 91.66ms (+13.8)
相關問題
- 1. SQL日期範圍拆分
- 2. 將Excel範圍拆分爲單個單元格
- 3. 將子範圍拆分成子範圍
- 4. 將列表拆分成字母範圍
- 5. 拆分範圍
- 6. 將日期範圍拆分爲列
- 7. php - 將日期範圍拆分爲塊
- 8. 將日期範圍拆分爲日期範圍塊
- 9. 基於分號將Varchar max字段拆分爲多個列
- 10. 將整個散列範圍拆分爲n個相等的範圍
- 11. 拆分多個數據範圍多行
- 12. 在配置單元中將相等部分的數字範圍拆分
- 13. 將varchar轉換爲時間範圍
- 14. 範圍混淆:如何將單個類C#項目拆分爲多個類?
- 15. 將日期範圍拆分爲幾個月
- 16. 將包含範圍的行拆分成多行,數目爲
- 17. T-SQL將字拆分爲字符
- 18. 將不同的varchar數據從一列拆分爲多個行
- 19. 日期範圍拆分
- 20. 將數字範圍比較爲兩個單元格值所定義的範圍
- 21. Oracle SQL按分隔符將單個行拆分爲多個
- 22. 將CGPoint數字拆分爲兩個CGFloat
- 23. 將一串字拆分爲單個字的數組
- 24. 從給定範圍拆分數組
- 25. Mysql的2個VARCHAR列數據範圍
- 26. 將單個單元格範圍更改爲列範圍
- 27. 將數字轉換爲數字範圍?
- 28. VBA - 將單個字符串拆分爲單個單元格
- 29. 在Oracle中將varchar拆分爲單獨的列
- 30. 求和拆分範圍在一個SQL查詢
您可以發佈任何到目前爲止,你已經嘗試並沒有奏效? – gabe3886