SQL "SELECT IN (Value1, Value2 ...)" 将值的变量传递到 GridView

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/342655/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 00:27:16  来源:igfitidea点击:

SQL "SELECT IN (Value1, Value2...)" with passing variable of values into GridView

sqlgridviewselectsession-variables

提问by

I have a strange encounter when creating a GridView using SELECT..WHERE..<field> IN (value1, val2...).

使用SELECT..WHERE..<field> IN (value1, val2...).

In the "Configure datasource" tab, if i hard code the values SELECT .... WHERE field1 in ('AAA', 'BBB', 'CCC'), the system works well.

在“配置数据源”选项卡中,如果我对值进行硬编码SELECT .... WHERE field1 in ('AAA', 'BBB', 'CCC'),则系统运行良好。

However, if I define a new parameter and pass in a concatenated string of values using a variable; be it a @session, Control or querystring; e.g. SELECT .... WHERE field1 in @SESSIONthe result is always empty.

但是,如果我定义一个新参数并使用变量传入一个连接的值字符串;无论是@session、Control 还是查询字符串;例如SELECT .... WHERE field1 in @SESSION结果总是空的。

I did another experiment by reducing the parameter content to only one single value, it works well.

我做了另一个实验,将参数内容减少到只有一个值,效果很好。

in short, if I hardcode a string of values, it works, if I pass a variable with single value only, it works, but if i pass a varialbe with two values; it failed.

简而言之,如果我对一串值进行硬编码,它会起作用,如果我只传递一个带有单个值的变量,它会起作用,但是如果我传递一个带有两个值的变量;它失败了。

Pls advise if I have make any mistake or it is a known bug.

请告知我是否犯了任何错误或者这是一个已知的错误。

BR SDIGI

BR SDIGI

回答by Hutcho

This works. Not sure how efficient it is though.

这有效。虽然不确定它的效率如何。

CREATE PROCEDURE [dbo].[get_bars_in_foo]
    @bars varchar(255)
AS
BEGIN
    DECLARE @query AS varchar(MAX)
    SET @query = 'SELECT * FROM [foo] WHERE bar IN (' + @bars + ')'
    exec(@query)
END

-- exec [get_bars_in_foo] '1,2,3,4'

回答by Andrew Rollings

Take a look at the answer to this question (which is very similar to yours)

看看这个问题的答案(和你的很相似)

Parameterize an SQL IN clause

参数化 SQL IN 子句

Which ultimately links (via a convoluted route) to this definitive answer:

最终链接(通过复杂的路线)到这个明确的答案:

http://www.sommarskog.se/arrays-in-sql.html

http://www.sommarskog.se/arrays-in-sql.html

回答by Mitchel Sellers

If you go to using a stored procedure, you can use this method, which I discussed in regards to how to do it in SQL.

如果您要使用存储过程,则可以使用此方法,我在关于如何在 SQL 中执行此操作时对此进行了讨论。