DbExtensions - How to create WHERE clause with OR conditions?

959 Views Asked by At

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?

3

There are 3 best solutions below

2
On

It's simpler than you think:

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

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"))
0
On

One can use:

.AppendClause("OR", ",", "NAME = {0}",new object[]{"TEST"});