2

I'm trying to create WHERE clause with OR conditions using DbExtensions.

I'm trying to generate SQL statement which looks like

SELECT ID, NAME
FROM EMPLOYEE
WHERE ID = 100 OR NAME = 'TEST'

My C# code is

var sql = SQL.SELECT("ID, FIRSTNAME")
             .FROM("EMPLOYEE")
             .WHERE("ID = {0}", 10)
             .WHERE("NAME = {0}", "TEST");

How do I get the OR seperator using the above mentioned DbExtensions library?

Max Toro
  • 28,282
  • 11
  • 76
  • 114
mahichR
  • 355
  • 3
  • 14

3 Answers3

1

I have found a definition for logical OR operator here

  public SqlBuilder _OR<T>(IEnumerable<T> items, string itemFormat, Func<T, object[]> parametersFactory) {
     return _ForEach(items, "({0})", itemFormat, " OR ", parametersFactory);
  }

And some code examples here

 public SqlBuilder Or() {

 int[][] parameters = { new[] { 1, 2 }, new[] { 3, 4} };

 return SQL
    .SELECT("p.ProductID, p.ProductName")
    .FROM("Products p")
    .WHERE()
    ._OR(parameters, "(p.CategoryID = {0} AND p.SupplierID = {1})", p => new object[] { p[0], p[1] })
    .ORDER_BY("p.ProductName, p.ProductID DESC");
 }

I think (by analogy with example) in your case code should be something like this (but I can't test it for sure):

var params = new string[] { "TEST" };

var sql = SQL.SELECT("ID, FIRSTNAME")
             .FROM("EMPLOYEE")
             .WHERE("ID = {0}", 10)
             ._OR(params, "NAME = {0}", p => new object[] { p })

Hope this helps :)


By the way... have you tried this way?

var sql = SQL.SELECT("ID, FIRSTNAME")
             .FROM("EMPLOYEE")
             .WHERE(string.Format("ID = {0} OR NAME = '{1}'", 10, "TEST"))
Max Toro
  • 28,282
  • 11
  • 76
  • 114
Andrey Morozov
  • 7,839
  • 5
  • 53
  • 75
0

It's simpler than you think:

var sql = SQL
   .SELECT("ID, FIRSTNAME")
   .FROM("EMPLOYEE")
   .WHERE("(ID = {0} OR NAME = {1})", 10, "TEST");
Max Toro
  • 28,282
  • 11
  • 76
  • 114
  • 1
    I need to add `OR` clause in a loop. One approach is to build the entier `WHERE` clause first and then use it as you mentioned above. I was looking something more fluent syntax. `var sql = SQL.SELECT("ID, FIRSTNAME") .FROM("EMPLOYEE") .WHERE("ID = {0}", 10) .WHERE_OR("NAME = {0}", "TEST");` – mahichR Sep 04 '13 at 13:46
  • 1
    An .Append_OR would be great to have here, i have use for it as well – Gillardo Jun 25 '15 at 05:07
0

One can use:

.AppendClause("OR", ",", "NAME = {0}",new object[]{"TEST"});
arghtype
  • 4,376
  • 11
  • 45
  • 60