Ответ 1
Вот удар в T-SQL Unpack:
CREATE FUNCTION [dbo].[UnpackStrings]
(
@original nvarchar(4000),
@delimiter nchar(1),
@zed nchar(1),
@escape nchar(1)
)
RETURNS
@unpacked TABLE
(
elementNumber INT IDENTITY(1,1),
element nvarchar(4000)
)
AS
BEGIN
DECLARE @next int;
DECLARE @c nchar(1);
DECLARE @pos int;
DECLARE @sb nvarchar(4000);
-- Special characters must be distinct.
IF ( (@delimiter = @escape) OR
(@zed = @escape) OR
(@delimiter = @zed) )
RETURN;
-- Null string return a null array
IF (@original IS NULL)
RETURN;
-- A single escape character represents an array with a single
-- empty element to differentiate from an empty array.
IF (@original = @escape)
BEGIN
INSERT @unpacked (element) VALUES ('');
RETURN;
END
-- Otherwise read through the string and unpack.
SET @pos = 1;
SET @sb = '';
SET @next = 0;
-- Fill the table variable with the rows for your result set
WHILE( (@pos <= LEN(@original)) AND @next IS NOT NULL )
BEGIN
SET @next = UNICODE(SUBSTRING(@original, @pos, 1));
IF (@next IS NULL)
BEGIN
IF (LEN(@sb) > 0)
INSERT @unpacked (element) VALUES (@sb);
SET @sb = '';
CONTINUE;
END
ELSE
BEGIN
SET @c = NCHAR(@next);
IF ( @c = @zed AND (LEN(@sb) = 0 OR LEN(@sb) IS NULL) )
BEGIN
INSERT @unpacked (element) VALUES (NULL);
-- need to peek at next character,
SET @next = UNICODE(SUBSTRING(@original, @pos+1, 1));
IF (@next IS NOT NULL)
BEGIN
SET @c = NCHAR(@next);
IF ( @c != @delimiter )
BEGIN
-- Peek at next character and it not delimiter,
-- bad format encountered.
BREAK;
END
END
SET @sb = NULL;
END
ELSE
BEGIN
IF ( @c = @delimiter )
BEGIN
IF (LEN(@sb) > 0 )
INSERT @unpacked (element) VALUES (@sb);
SET @sb = '';
END
ELSE
BEGIN
IF ( @c = @escape )
BEGIN
SET @pos = @pos + 1;
SET @next = UNICODE(SUBSTRING(@original, @pos, 1));
IF (@next IS NULL )
BEGIN
CONTINUE;
END
ELSE
BEGIN
SET @sb = @sb + NCHAR(@next);
END
END
ELSE
BEGIN
SET @sb = @sb + @c;
END
END
END
--
END
SET @pos = @pos + 1;
END
--
-- Likely not needed. This is handled above.
--
-- A final zed character will made sb = null,
-- but otherwise we have an additional element.
IF (@sb IS NOT NULL )
INSERT @unpacked (element) VALUES (@sb);
RETURN
END