下面的查询有一个参数与字符串列表分配:添加一个字符串列表来OracleCommand.Parameters在C#
select * from a_table where something in :list_of_strings
我有一个C#List<string>
我想分配给list_of_strings
参数。
鉴于OracleCommand
(代表上述查询),我如何将我的List<string>
绑定到命令的list_of_strings
参数?
下面的查询有一个参数与字符串列表分配:添加一个字符串列表来OracleCommand.Parameters在C#
select * from a_table where something in :list_of_strings
我有一个C#List<string>
我想分配给list_of_strings
参数。
鉴于OracleCommand
(代表上述查询),我如何将我的List<string>
绑定到命令的list_of_strings
参数?
实际上,您不能将单个参数绑定到值列表。在这种情况下,您可以将值连接到查询字符串。
但是,这是因为有一个限制你可以在IN
条款上的值的限制。
List<string> list = new List<string>();
list.Add("1");
list.Add("2");
list.Add("3");
list.Add("4");
string listStr = string.Join(",", list);
//result: "1,2,3,4"
如果你的字符串列表是一个字符串列表,你可以这样做:
List<string> list = new List<string>();
list.Add("one");
list.Add("two");
list.Add("three");
list.Add("four");
string listStr = string.Concat("'", string.Join("','", list), "'");
//result: "'one','two','three','four'"
查询字符串:
string query = string.Format("select * from a_table where something in({0})", listStr);
观测值:您可能需要处理的可能性,其中该列表是空的。
另一种可能性是将所有值插入临时表并在select语句中使用它。这将有无限的字符串值的优势,避免对DBMS一个新的硬解析相比串接技术:
SELECT *
FROM A_TABLE
WHERE SOMETHING IN(SELECT SOMETHING FROM TEMP_TABLE)
小心点。如果你没有清理你的列表参数,你可以打开自己的SQL注入。 – 2016-05-23 20:21:42
如果不知道这个问题是类似http://stackoverflow.com/questions/6155146/问题使用的oracle参数在选择或不选择。 – 2013-02-10 14:43:09
这可能对你有所帮助。 http://asktom.oracle.com/pls/asktom/f?p=100:11:::::P11_QUESTION_ID:139812348065 – OldProgrammer 2013-02-10 17:11:33