2015-04-12 25 views
-1

當輸入變量不爲空時,我想使用where如何使用變量不爲空時的位置

例如,當@custid不爲null創建此查詢:

Select * 
from customers 
where custid = @custid 

@custid爲空,然後使用這個查詢,而不是:

Select * 
from customers 

我怎樣才能做到這一點?

我在谷歌搜索,但還沒有找到任何相似的答案。由於

回答

4

您可以使用下面的查詢:

Select * 
from customers 
where @custid IS NULL OR [email protected] 

在這種情況下,如果你的變量爲空僅條件@custid IS NULL進行評估,你會得到的查詢相同Select * from customers

如果變量是不null然後條件@custid IS NULL是假的,你的查詢是相同的Select * from customers where [email protected]

0

我使用SqlBuilder類,並提供過濾器,附加的WHERE子句programmatical LY。

所以SqlBuilder類是這樣的:

public class Program 
{ 
    public static void Main() 
    { 
     Console.WriteLine(SqlBuilder.GetSql(null)); 
     Console.WriteLine(SqlBuilder.GetSql("CUSTOMER_ID")); 
    } 

    public class SqlBuilder{ 

     private static string _baseSql = "select * from customers"; 

     public static string GetSql(string customerId){ 
      var final = _baseSql; 
      if(customerId != null) 
       final += " WHERE [email protected]"; 
      return final; 
     } 
    } 
} 

這也可以通過使用參數和枚舉製造的仿製。

+0

聽起來像你已經寫了一個ORM的一部分,是否有任何理由,你不會只是使用輕量級的ORM? – Charleh

+0

我實際上將它與Dapper一起使用。我使用的當前數據庫名稱非常糟糕,因此我必須重命名它們以使代碼可讀。它也在DB2中,因此有很多ORM不能正確生成SQL。 – druidicwyrm

相關問題