2014-01-06 191 views
0

我已經構建了我的sql statemnet像下面的方式,但我嘗試編譯時出現錯誤。我知道我們可以在字符串中動態構建它,但是想知道我們可以像這樣寫語句。請尋求建議。SQL Server存儲過程SELECT語句與幾個IF語句

INSERT INTO #tmpHierarchy ( 
JID , 
EntryDate , 
RefundDate , 
ActionBy , 
Comments , 
CID, 
nLevel 
)  
SELECT 
    JID, EntryDate, RefundDate, ActionBy, Comments, CID, nLevel 
FROM 
    Hierarchy 
WHERE 1=1 
    AND 
IF @FromDate <> '' AND @ToDate <> '' 
BEGIN 
    Convert(varchar,EntryDate,112)>= @FromDate AND Convert(varchar,EntryDate,112) <= @ToDate 
END 

IF @ActionBy <> '' 
BEGIN 
    [email protected] 
END 

IF @JID > 0 
BEGIN 
    [email protected] 
END 

回答

0

實際上,你必須建立一個varchar與查詢,然後執行它:

declare @sql varchar(max) 

set @sql = 'INSERT INTO #tmpHierarchy ( 
JID , 
EntryDate , 
RefundDate , 
ActionBy , 
Comments , 
CID, 
nLevel 
)  
SELECT JID,EntryDate,RefundDate,ActionBy,Comments,CID,nLevel FROM Hierarchy WHERE 1=1' 

IF @FromDate <> '' AND @ToDate <> '' 
BEGIN 
    @sql = @sql + ' and Convert(varchar,EntryDate,112)>= @FromDate AND Convert(varchar,EntryDate,112) <= @ToDate' 
END 

IF @ActionBy <> '' 
BEGIN 
    @sql = @sql + ' and [email protected]' 
END 

IF @JID > 0 
BEGIN 
    @sql = @sql + ' and [email protected]' 
END 

exec (@sql) 
+0

沒有使動態SQL不能我們這樣做? – Thomas

+0

因爲你的轉換函數可能有點兒樂趣 - 如果你的值無效,你不想讓它執行。 – Szymon

0

,你結合IF語句到WHERE條款

SELECT JID, EntryDate, RefundDate, ActionBy, Comments, CID, nLevel 
FROM Hierarchy 
WHERE 1 = 1 
AND (@FromDate = '' OR @ToDate = '' OR (Convert(varchar, EntryDate, 112) >= @FromDate AND Convert(varchar, EntryDate, 112) <= @ToDate)) 
AND (@ActionBy = '' OR ActionBy = @ActionBy) 
AND (@JID <= 0 OR JID = @JID) 
你可以做這樣的事情