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

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

SQL where clause with multiple “OR” conditions dynamically

问题

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

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

  1. Select * from table
  2. where
  3. (Name = @name and Account = @account)
  4. OR
  5. (Name = @name and Account = @account)
  6. OR
  7. (Name = @name and Account = @account)
  8. OR
  9. (Name = @name and Account = @account)
  10. OR
  11. …….

这里的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.

  1. Select * from table
  2. where
  3. (Name = @name and Account = @account)
  4. OR
  5. (Name = @name and Account = @account)
  6. OR
  7. (Name = @name and Account = @account)
  8. OR
  9. (Name = @name and Account = @account)
  10. OR
  11. ……..

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

  1. 例如:
  2. ```c#
  3. var names = new[] {"name1", "name2", "name3"};
  4. var accounts = new[] {"account1", "account2", "account3"};
  5. var conditions = new List<string>();
  6. var command = new SqlCommand();
  7. for (var i = 0; i < names.Length; i++)
  8. {
  9. conditions.Add($"(Name = @Name{i} AND Account = @Account{i})");
  10. command.Parameters.Add($"@Name{i}", SqlDbType.VarChar, 50).Value = names[i];
  11. command.Parameters.Add($"@Account{i}", SqlDbType.VarChar, 50).Value = accounts[i];
  12. }
  13. command.CommandText = $"SELECT * FROM MyTable WHERE {string.Join(" OR ", conditions)}";
英文:

E.g.

  1. var names = new[] {&quot;name1&quot;, &quot;name2&quot;, &quot;name3&quot;};
  2. var accounts = new[] {&quot;account1&quot;, &quot;account2&quot;, &quot;account3&quot;};
  3. var conditions = new List&lt;string&gt;();
  4. var command = new SqlCommand();
  5. for (var i = 0; i &lt; names.Length; i++)
  6. {
  7. conditions.Add($&quot;(Name = @Name{i} AND Account = @Account{i})&quot;);
  8. command.Parameters.Add($&quot;@Name{i}&quot;, SqlDbType.VarChar, 50).Value = names[i];
  9. command.Parameters.Add($&quot;@Account{i}&quot;, SqlDbType.VarChar, 50).Value = accounts[i];
  10. }
  11. 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:

确定