本文介绍了使用 UDF 拆分值对和创建表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试编写一个表值函数,该函数将值对作为参数并返回一个包含两列的表.

I've been trying to write a Table-Valued function that takes value pairs as a parameter and return a table with two columns.

下面是我想要做的函数签名.

Below is the function signature I am trying to do.

FUNCTION [dbo].[ValuePairParser]( @DelimitedValuePairs VARCHAR(MAX),
                                  @Delimiter CHAR(1),
                                  @ValuePairDelimiter CHAR(1) )
  RETURNS @ValuePairTable
  TABLE ( Id INT, Code INT )

我想调用如下方法

@ValuePairs VARCHAR(MAX) = '1:1, 1:2, 1:4, 2:3, 1000:230, 130:120,'

ValuePairParser (@ValuePairs, ',', ':')

您能看到在 ValuePairs 字符串上方拆分并创建包含两列的表格的任何好方法吗?

Can you see any nice way to split above ValuePairs sting and create a table with two columns?

推荐答案

CREATE FUNCTION [dbo].[SplitWithPairs]
(
    @List NVARCHAR(MAX),
    @MajorDelimiter VARCHAR(3) = ',',
    @MinorDelimiter VARCHAR(3) = ':'
)
RETURNS @Items TABLE
(
    Position  INT IDENTITY(1,1) NOT NULL,
    LeftItem  INT NOT NULL,
    RightItem INT NOT NULL
)
AS
BEGIN
    DECLARE
        @Item      NVARCHAR(MAX),
        @LeftItem  NVARCHAR(MAX),
        @RightItem NVARCHAR(MAX),
        @Pos       INT;

    SELECT
        @List = @List + ' ',
        @MajorDelimiter = LTRIM(RTRIM(@MajorDelimiter)),
        @MinorDelimiter = LTRIM(RTRIM(@MinorDelimiter));

    WHILE LEN(@List) > 0
    BEGIN
        SET @Pos = CHARINDEX(@MajorDelimiter, @List);

        IF @Pos = 0
            SET @Pos = LEN(@List) + LEN(@MajorDelimiter);

        SELECT
            @Item = LTRIM(RTRIM(LEFT(@List, @Pos - 1))),
            @LeftItem = LTRIM(RTRIM(LEFT(@Item,
            CHARINDEX(@MinorDelimiter, @Item) - 1))),
            @RightItem = LTRIM(RTRIM(SUBSTRING(@Item,
            CHARINDEX(@MinorDelimiter, @Item)
            + LEN(@MinorDelimiter), LEN(@Item))));

        INSERT @Items(LeftItem, RightItem)
            SELECT @LeftItem, @RightItem;

        SET @List = SUBSTRING(@List,
            @Pos + LEN(@MajorDelimiter), DATALENGTH(@List));
    END
    RETURN;
END
GO

DECLARE @ValuePairs VARCHAR(MAX) = '1:1, 1:2, 1:4, 2:3,1000:230, 130:120,';

SELECT LeftItem, RightItem
  FROM dbo.SplitWithPairs(@ValuePairs, ',', ':')
  ORDER BY Position;
GO

这篇关于使用 UDF 拆分值对和创建表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-11 20:41