我創建了一個循環遍歷每個迭代集,直到達到字符串的長度。使用你的榜樣值的測試
CREATE PROCEDURE [dbo].[SplitMyFunkyText] @Source nvarchar(MAX)
AS
DECLARE @Results AS TABLE(Part NVARCHAR(22))
DECLARE @I INT = 1
WHILE @I < LEN(@Source)
BEGIN
INSERT INTO @Results
SELECT SUBSTRING(@Source, @I, 22)
SET @I = @I + 23
END
SELECT * FROM @Results
GO
這裏:
DECLARE @Source AS NVARCHAR(230)
SET @Source = '123 870503-23-5370 021 456 830503-23-5371 031 789 870103-11-5372 041 654 870501-23-5373 051 321 880503-12-5374 061 987 870803-23-5375 071 109 870508-06-5376 081 174 810503-03-5377 091 509 870103-01-5378 101 687 870501-12-5379 131'
EXEC SplitMyFunkyText @Source
以下是測試結果:
123 870503-23-5370 021
456 830503-23-5371 031
789 870103-11-5372 041
654 870501-23-5373 051
321 880503-12-5374 061
987 870803-23-5375 071
109 870508-06-5376 081
174 810503-03-5377 091
509 870103-01-5378 101
687 870501-12-5379 131
按你的第二個問題:然後釀是到存儲過程中「如果我的拆分記錄不在固定位置「
您最初表示」固定長度「,這很容易。
CREATE PROCEDURE [dbo].[SplitMyFunkyText]
@Source nvarchar(MAX)
AS
DECLARE @Results AS TABLE(Part NVARCHAR(22))
DECLARE @I INT = 1
DECLARE @NextLength INT = -1
DECLARE @SubPart1 NVARCHAR(20)
DECLARE @SubPart2 NVARCHAR(20)
DECLARE @SubPart3 NVARCHAR(20)
WHILE @I < LEN(@Source)
BEGIN
-- GET 1st SubPart -----------------------------------
SET @NextLength = CHARINDEX(' ',@Source,@I)
IF @NextLength > 0
SET @SubPart1 = SUBSTRING(@Source, @I, @NextLength - @I)
ELSE
SET @SubPart1 = SUBSTRING(@Source, @I, LEN(@Source))
SET @I = @I + LEN(@SubPart1) + 1;
-- GET 2st SubPart -----------------------------------
SET @NextLength = CHARINDEX(' ',@Source,@I)
IF @NextLength > 0
SET @SubPart2 = SUBSTRING(@Source, @I, @NextLength - @I)
ELSE
SET @SubPart2 = SUBSTRING(@Source, @I, LEN(@Source))
SET @I = @I + LEN(@SubPart2) + 1;
-- GET 3st SubPart -----------------------------------
SET @NextLength = CHARINDEX(' ',@Source,@I)
IF @NextLength > 0
SET @SubPart3 = SUBSTRING(@Source, @I, @NextLength - @I)
ELSE
SET @SubPart3 = SUBSTRING(@Source, @I, LEN(@Source))
SET @I = @I + LEN(@SubPart3) + 1;
INSERT INTO @Results
SELECT @SubPart1 + ' ' + @SubPart2 + ' ' + @SubPart3
END
SELECT * FROM @Results
GO
這裏是一個更精簡版本,隨着3組非定長字段的工作:爲了記錄不固定長度的下面會,只要它在與空間的3組之間的工作
CREATE PROCEDURE [dbo].[SplitMyFunkyText]
@Source nvarchar(MAX)
AS
DECLARE @Results AS TABLE(Part NVARCHAR(255))
DECLARE @I INT = 1
DECLARE @Start INT = 1
WHILE @I > 0
BEGIN
SET @Start = @I
SET @I = CHARINDEX(' ',@Source, 1+CHARINDEX(' ',@Source, 1+CHARINDEX(' ', @Source, @I + 1)))
IF @I > 0
INSERT INTO @Results
SELECT SUBSTRING(@Source, @Start, @I - @Start)
ELSE
INSERT INTO @Results
SELECT SUBSTRING(@Source, @Start, LEN(@Source))
END
SELECT * FROM @Results
GO
谷歌:「SQL Server的分裂」 –