質問

Using MS SQL Studio, I need to parse two comma delimited fields that align to each other. For example:

Name           Pet_Name            Type
Bob            Sally,Betty,Sue     Cat,Dog,Cat
Dick           Mary,Fido,Polly     Dog,Dog,Bird

Parsed to:
Name           Pet_Name            Type
Bob            Sally               Cat
Bob            Betty               Dog
Bob            Sue                 Cat
Dick           Mary                Dog
Dick           Fido                Dog
Dick           Polly               Bird 

With all the pet names matching up to their respective type. Any thoughts?

役に立ちましたか?

解決

Create an input table.

CREATE TABLE dbo.Input
(
    Name NVARCHAR(25) NOT NULL PRIMARY KEY,
    Pet_Names NVARCHAR(200) NOT NULL,
    Types NVARCHAR(200) NOT NULL
);

INSERT INTO dbo.Input (Name, Pet_Names, Types)
VALUES
    (N'Bob', N'Sally,Betty,Sue', N'Cat,Dog,Cat'), 
    (N'Dick', N'Mary,Fido,Polly', N'Dog,Dog,Bird');

Create a user-defined table function which splits the Pet_Names and Types.

CREATE FUNCTION dbo.ufn_Split
(
    @name NVARCHAR(25),
    @pet_names NVARCHAR(200),
    @types NVARCHAR(200)
)
RETURNS @ret TABLE
(
    Name NVARCHAR(25),
    Pet_Name NVARCHAR(25),
    Type NVARCHAR(25)
)
AS
BEGIN
    DECLARE @pet_names2 NVARCHAR(200);
    DECLARE @types2 NVARCHAR(200);
    DECLARE @i INT;
    DECLARE @j INT;
    DECLARE @p NVARCHAR(25);
    DECLARE @t NVARCHAR(25);

    SET @pet_names2 = @pet_names;
    SET @types2 = @types;

    WHILE LEN(@pet_names2) > 0 AND LEN(@types2) > 0
    BEGIN
        SET @i = CHARINDEX(N',', @pet_names2);
        SET @j = CHARINDEX(N',', @types2);

        IF @i > 0 AND @j > 0
        BEGIN
            SET @p = SUBSTRING(@pet_names2, 1, @i-1);
            SET @pet_names2 = SUBSTRING(@pet_names2, @i+1, LEN(@pet_names2)-@i);

            SET @t = SUBSTRING(@types2, 1, @j-1);
            SET @types2 = SUBSTRING(@types2, @j+1, LEN(@types2)-@j);
        END
        ELSE
        BEGIN
            SET @p = @pet_names2;
            SET @pet_names2 = NULL;

            SET @t = @types2;
            SET @types2 = NULL;
        END

            INSERT INTO @ret (Name, Pet_Name, Type)
                VALUES(@Name, @p, @t);
    END

    RETURN
END;

Run a select statement.

SELECT T.*
    FROM dbo.Input AS I
        CROSS APPLY dbo.ufn_Split(I.Name, I.Pet_Names, I.Types) AS T;

Results

Name        Pet_Name    Type
Bob         Sally       Cat
Bob         Betty       Dog
Bob         Sue         Cat
Dick        Mary        Dog
Dick        Fido        Dog
Dick        Polly       Bird

Code written in T-SQL and tested on SQL Server 2012.

Caveat this is demo code and not robust enough for a production system. You'd have to consider error cases like different number of items in Pet_Names and Types.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top