我一直在尝试编写一个表值函数,该函数将值对作为参数并返回一个包含两列的表。
以下是我要执行的功能签名。
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字符串上方拆分并创建包含两列的表的任何好方法吗?
最佳答案
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
关于sql - 使用UDF拆分值对和创建表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6673982/