2012-10-16 84 views
0

我有下面的工作,但想知道如果我下面有什麼可以優化或如果有更好的方式做dynamive查詢。tsql動態sql最佳方法

我有一個網頁表單,用戶輸入一個位置和收集日期。對於收集的日期,我收集了收集日期和收集日期。用戶將收件日期保留爲空,在這種情況下,它將執行比收集起始日期更長的任何操作。

請注意我如何在下面的IS NOT NULL和1 = 1。還想知道如果動態SQL是最好的方法,或者是否有一個更簡單的方法來做到這一點。

DECLARE @sql varchar(max); 

    SET @sql = 'SELECT * from tblProgram WHERE 1=1' 

    IF (@Location IS NOT NULL) 
    BEGIN 
     SET @sql = @sql + ' AND Location = ' + @Location 
    END  

    IF (@FromDateCollected IS NOT NULL AND @ToDateCollected IS NOT NULL) 
    BEGIN 
     SET @sql = @sql + ' AND pw.DateCollected >= ' + QUOTENAME(convert(varchar, @FromDateCollected,101),'''') 
     + ' AND pw.DateCollected <= ' + QUOTENAME(convert(varchar, @ToDateCollected,101),'''') 

    END 
    ELSE IF (@FromDateCollected IS NOT NULL AND @ToDateCollected IS NULL) 
    BEGIN 
     SET @sql = @sql + ' AND pw.DateCollected >= ' + QUOTENAME(convert(varchar, @FromDateCollected,101),'''') 

    END 

    exec(@sql) 
+0

正常SQL有什麼問題? 'WHERE x是null還是x> date_column'? –

+0

pw從哪裏來? –

回答

4

那麼你可以做ta.speot.is評論使用靜態SQL並做

WHERE x is null or x > date_column? 

但是如果你堅持使用動態SQL,你應該使用使用sp_executeSQL

參數化的SQL語句

它更易於閱讀,您不必使用quotename,而且您可以免受SQL注入攻擊

DECLARE @Location int 
DECLARE @FromDateCollected datetime 
DECLARE @ToDateCollected datetime 
SET @ToDateCollected = '1/02/2012' 



DECLARE @sql nvarchar(max) 
DECLARE @ParmDefinition nvarchar(max) 

SET @ParmDefinition = N'@Location int , @FromDateCollected datetime, @ToDateCollected datetime '; 

SET @sql = N'SELECT * from tblProgram WHERE 1=1' 

IF (@Location IS NOT NULL) 
BEGIN 
    SET @sql = @sql + N' AND Location = @Location' 
END  

IF (@FromDateCollected IS NOT NULL AND @ToDateCollected IS NOT NULL) 
BEGIN 
    SET @sql = @sql + N' AND pw.DateCollected >= @FromDateCollected ' 
     + N' AND pw.DateCollected <= @ToDateCollected ' 

END 
ELSE IF (@FromDateCollected IS NOT NULL AND @ToDateCollected IS NULL) 
BEGIN 
    SET @sql = @sql + N' AND pw.DateCollected >= @FromDateCollected' 

END 

exec sp_executesql @SQL, @ParmDefinition, @Location = @Location, 
            @FromDateCollected = @FromDateCollected, 
             @ToDateCollected = @ToDateCollected 

DEMO