SQL中的WHERE子句具有多个“OR”条件,动态生成。

huangapple go评论62阅读模式
英文:

SQL where clause with multiple “OR” conditions dynamically

问题

我有一个C# Windows应用程序,从SQL数据库中获取数据。

我需要编写一个带有多个“OR”条件的动态WHERE子句的SQL查询。

Select * from table 
where 
(Name = @name and Account = @account)
OR
(Name = @name and Account = @account)
OR
(Name = @name and Account = @account)
OR
(Name = @name and Account = @account)
OR
…….

这里的OR语句的数量可以根据数据表中的行数变化而变化。

如何编写一个可以动态使用OR语句的SQL查询?

英文:

I have a c# windows application where I get data from SQL database.

I need to write an sql query with where clause having multiple “OR” conditions dynamically.

Select * from table 
where 
(Name = @name and Account = @account)
OR
(Name = @name and Account = @account)
OR
(Name = @name and Account = @account)
OR
(Name = @name and Account = @account)
OR
……..

Here number of OR statement can vary based on the number of rows in the data table.

How can write a sql query that can use OR statements dynamically?

答案1

得分: 3

例如:
```c#
var names = new[] {"name1", "name2", "name3"};
var accounts = new[] {"account1", "account2", "account3"};
var conditions = new List<string>();
var command = new SqlCommand();

for (var i = 0; i < names.Length; i++)
{
    conditions.Add($"(Name = @Name{i} AND Account = @Account{i})");
    command.Parameters.Add($"@Name{i}", SqlDbType.VarChar, 50).Value = names[i];
    command.Parameters.Add($"@Account{i}", SqlDbType.VarChar, 50).Value = accounts[i];
}

command.CommandText = $"SELECT * FROM MyTable WHERE {string.Join(" OR ", conditions)}";
英文:

E.g.

var names = new[] {&quot;name1&quot;, &quot;name2&quot;, &quot;name3&quot;};
var accounts = new[] {&quot;account1&quot;, &quot;account2&quot;, &quot;account3&quot;};
var conditions = new List&lt;string&gt;();
var command = new SqlCommand();

for (var i = 0; i &lt; names.Length; i++)
{
    conditions.Add($&quot;(Name = @Name{i} AND Account = @Account{i})&quot;);
    command.Parameters.Add($&quot;@Name{i}&quot;, SqlDbType.VarChar, 50).Value = names[i];
    command.Parameters.Add($&quot;@Account{i}&quot;, SqlDbType.VarChar, 50).Value = accounts[i];
}

command.CommandText = $&quot;SELECT * FROM MyTable WHERE {string.Join(&quot; OR &quot;, conditions)}&quot;;

This still uses parameters so it still avoids the possibility of SQL injection but it also allows you to build the query dynamically.

huangapple
  • 本文由 发表于 2023年2月6日 09:04:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/75356567.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定