拆分值对并使用 UDF 创建表
我一直在尝试编写一个表值函数,它将值对作为参数并返回一个包含两列的表。
下面是我想要做的函数签名。
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 字符串并创建一个包含两列的表吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
十年后回顾,今天肯定有更好的方法来做到这一点。
SQL Server 2022、Azure SQL 数据库、托管实例
(示例)
SQL Server 2016 - 2019
(示例)
在 SQL Server 2016 中通过2019 年,进行了一些更改:
STRING_SPLIT
在 SQL Server 2022 之前不支持序数,因此我们可以使用OPENJSON
而LTRIM/RTRIM
> 由于 SQL Server 2017 中添加了TRIM
key
是从 0 开始的,因此我们增加 1 以获得等效的从 1 开始的位置关于此函数的缺点是,在不更改函数的情况下,您不能使用
,
作为次分隔符,因为,
是OPENJSON
的分隔方式。您可能希望保留其他字符作为这两个分隔符。不再支持的版本
最后,原始答案适用于 SQL Server 2016 之前的版本,我将保持原样,但有一个免责声明,它可以改进(不乏有关那里的阅读这里 以及一般来说,多语句表值函数(特别是带有循环的函数)是一个大危险信号):
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):