在逗号上拆分 sql 参数 [英] Split sql parameter on comma

查看:28
本文介绍了在逗号上拆分 sql 参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码适用于主流"或高级"作为参数,但是我试图使其对它们都适用,如下所示,但它不返回任何结果.我怎样才能使下面的代码工作?

Below code works for 'Main Stream' or 'Premium' as parameter, however I am trying to make it work for both of them as you can see below, but it doesn't return any results. How can I make the below code work?

declare @myParameter varchar(50)
SET @myParameter = 'Main Stream , Premium'


select * FROM sales  
where myCategory IN (@myParameter)

推荐答案

你可以尝试类似的事情

--Split
DECLARE @textXML XML
DECLARE @data NVARCHAR(MAX), 
        @delimiter NVARCHAR(5)
        
SELECT  @data = 'Main Stream , Premium',
        @delimiter = ','
        
SELECT    @textXML = CAST('<d>' + REPLACE(@data, @delimiter, '</d><d>') + '</d>' AS XML)
SELECT  T.split.value('.', 'nvarchar(max)') AS data
FROM    @textXML.nodes('/d') T(split)

您可以将其存储在临时表中,也可以在 IN 子句中使用它.

You could either store this in a temp table, or use it in the IN clause.

@Hoy 评论

您可以查看 nodes() 方法(xml 数据类型)

nodes() 方法在你想分解 xml 数据类型时很有用实例转化为关系数据.它允许您识别节点将被映射到一个新行.

The nodes() method is useful when you want to shred an xml data type instance into relational data. It allows you to identify nodes that will be mapped into a new row.

另外,请查看 xml 数据类型方法

然后您可以将其用作

select * 
FROM    sales  
where   myCategory IN   (
                            SELECT  T.split.value('.', 'nvarchar(max)')
                            FROM    @textXML.nodes('/d') T(split)
                        )

这篇关于在逗号上拆分 sql 参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆