2013-07-26 61 views
0

我有一個情況,其中參數我的sql查詢將dynamic.if參數爲空我不想將其添加到查詢,我已經嘗試了一些事情(從未工作過)..它現在看起來像stoopid我建立動態sql查詢之間和按關鍵字排序

ds = SqlHelper.ExecuteDataset(GlobalSettings.DbDSN, CommandType.Text, "SELECT TOP 1000 [ID],[Project],[Owner],[Consultant],[Contractor],[Value],[Level1],[Level2] ,[Status] ,[Category] ,[Country],[CreatedDate],[CreatedByID],[CreatedByName] FROM [tbl_Projects] where"+if(!string.IsNullOrEmpty(paraCategory)){ "[Category] = @Category and"}+"+ Country [email protected] and "+if(!string.IsNullOrEmpty(paraCategory)){ " value between @val1 and @val2"}+" order by CreatedDate asc", 
            new SqlParameter("@Category", paraCategory), 
             new SqlParameter("@Country", paraCountry), 
             new SqlParameter("@val1", paraValue1), 
                 new SqlParameter("@val2", paraValue2)); 

我已經檢查了構建動態SQL還 here 但它不是有用的,我需要把像和words..can任意一個鍵之間幫我一下嗎?

+0

這看起來像C#給我。你能否相應地標記你的問題? –

+0

@FabianBigler是的,我已經添加了一些C#代碼到我的SQL查詢來處理這..這是愚蠢的..現在我試圖通過SQL本身解決這..這是這篇文章的原因。我也編輯了標籤正如你所說的..如果解決方案只用C#我不想錯過它 – Athul

+0

行。我希望我的回答能幫助你。其實很簡單。 –

回答

1

只給你一個想法,我會做這樣的事情:

var sql as new StringBuilder(); 
sql.Append("SELECT ... all your columns ... FROM yourTable"); 
var parameters as new List(Of SqlParameter); 
if (!string.IsNullOrEmpty(paraCategory) 
{ 
    sql.Append("[Category][email protected],"); 
    parameters.AddWithvalue("@Category", paraCategory); 
} 
sql.Length -= 1 

//...your other parameters... 

sql.Append("ORDER BY CreatedDate"); 

然後這一切傳遞給您提供SQLHelper:

ds = SqlHelper.ExecuteDataset(GlobalSettings.DbDSN, CommandType.Text, sql.ToString(), parameters); 

還要注意的是,上面的代碼是不是真的防守。因此,例如,如果沒有參數傳遞,它將失敗。由於我不知道SqlHelper-Class,因此可能需要其他東西而不是List(Of SqlParameter)。

+0

您可以簡單地重載'ExecuteDataset',以便在不需要時可以省略'parameters'參數。 – Tobsey

+0

我不確定,但是,這個代碼是不是我的c#文件裏面工作..主要是這行 var參數作爲新的List(Of SqlParameter); 我需要添加任何命名空間xtra嗎? – Athul

+0

是的。用於StringBuilder的NameSpace System.Text。 和System.Collections.Generic for List(Of SqlParameter) –

1

變化SqlHelper.ExecuteDataset因此,它需要一個委託調用所需的特定代碼:

class SqlHelper 
{ 
    public delegate void SqlCommandDelegate(SqlCommand command); 

    public Dataset ExecuteDataset(string dsn, 
      CommandType commandType, 
      SqlCommandDelegate specificPreparations) 
    { 
     Dataset results; 
     using (SqlConnection conn = new SqlConnection()) 
     { 
      conn.ConnectionString = dsn; 
      using (SqlCommand command = conn.CreateCommand()) 
      { 
       command.CommandType = commandType; 
       connection.Open(); 
       specificPreparations(command); 
       SqlDataReader reader = command.ExecuteReader(); 
       results.Load(reader); 
      } 
     } 

     return results; 
    } 
} 

然後調用它:

ds = SqlHelper.ExecuteDataset(GlobalSettings.DbDSN, 
    CommandType.Text, 
    delegate(SqlCommand command) 
    { 
     command.CommandText = "SELECT BLAH FROM BLAH"; 

     foreach (var myParameter in myParameterList) 
     { 
      SqlParameter p = new SqlParameter(); 
      // Construct p 
      command.Paramters.Add(p) 
     } 
     // Anything else you want to do to the command 
    }); 
} 
1

您可以使用SP

CREATE PROCEDURE MyDynamicSP(@Condition1 as varchar(100),Condition2 as varchar(100),Condition3 as varchar(100)) 
    AS 
    SET NOCOUNT ON 

    DECLARE @STRSQL VARCHAR(1000) 

    SET @STRSQL = 'SELECT * FROM MyTable WHERE ' 
    IF NOT @Condition1 IS NULL 
     @STRSQL = @STRSQL + ' ' + @Condition1 

    IF NOT @Condition2 IS NULL 
     @STRSQL = @STRSQL + ' ' + @Condition2 

    IF NOT @Condition3 IS NULL 
     @STRSQL = @STRSQL + ' ' + @Condition3 

    EXEC sp_executesql @STRSQL 

    SET NOCOUNT OFF 
做到這一點
1

您可以在查詢內部進行如下測試:

SELECT *whatever you need* 
    FROM [tbl_Projects] 
    where 
     (@Category is null or [Category] = @Category) and 
     (@Country is null or [Country] = @country) and 
     (@val1 is null or value > @val1) and 
     (@val2 is null or value < @val2)  
    order by CreatedDate asc 

而且你總是發送4個參數。另外,您可以在SQL工作表中構建查詢,並且更容易發現語法錯誤等。

雖然您可能需要爲什麼是空值添加一些測試。