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 )
I want to call the method like below
@ValuePairs VARCHAR(MAX) = '1:1, 1:2, 1:4, 2:3, 1000:230, 130:120,'
ValuePairParser (@ValuePairs, ',', ':')
Can you see any nice way to split above ValuePairs sting and create a table with two columns?
2条答案
按热度按时间mwg9r5ms1#
Revisiting after a decade there are definitely better ways to do this today.
SQL Server 2022, Azure SQL Database, Managed Instance
( example )
SQL Server 2016 - 2019
( example )
In SQL Server 2016 through 2019, a few changes:
STRING_SPLIT
doesn't support ordinal until SQL Server 2022, so we can useOPENJSON
insteadLTRIM/RTRIM
sinceTRIM
was added in SQL Server 2017key
is 0-based so we bump by 1 to get an equivalent 1-based positionOne note about this function is that you can't use
,
as the minor delimiter without changing the function, since,
is howOPENJSON
delimits. There are probably other characters you may want to stay from for both delimiters.Versions no longer supported
And finally, the original answer, which will work on versions older than SQL Server 2016, I'll leave as it was, but with a disclaimer that it could be improved (no shortage of reading about there here and, generally, multi-statement table-valued functions - particularly with loops - are a big red flag):
e7arh2l62#