這裏是我的存儲過程:如何檢查兩個日期是否在SQL存儲過程的某個日期範圍內?
ALTER Procedure [dbo].[SearchCreatedAssignments]
(@LessonName NVarchar(MAX), @DateFrom date, @DateTo Date, @LocationCode NVarchar(MAX))
As
BEGIN
Select *
from dbo.CreatedAssignments
--IsNull replaces NULL with the specified replacement value.
--IsNull(check_expression, replacement_value)
--NullIf returns a null value if the two specified expressions are equal.
--In other words, NULLIF returns the first expression if the two expressions are not equal.
--If the expressions are equal, NULLIF returns a null value of the type of the first expression.
where LessonName = IsNull(NullIf(@LessonName,''),LessonName)
AND StartDate = IsNull(NullIf(@DateFrom,''),StartDate)
AND EndDate = IsNull(NullIf(@DateTo,''),EndDate)
AND LocationCode = IsNull(NullIf(@LocationCode,''),LocationCode)
AND status ='a'
END
正如你所看到的,此存儲過程設置,使用戶可以通過任何一個搜索標準,或者搜索條件的任意組合進行搜索(條件是列名),而將其他標準留空。例如,假設用戶只想通過lessonname
搜索數據庫。這個存儲過程允許用戶做到這一點。它將返回與指定的lessonname
匹配的所有結果,而不管其他條件是否保留爲空。所以,這裏是我的問題:我怎麼能保留這個邏輯,但返回的結果在哪裏的日期範圍內的startdate
和enddate
?我知道我需要使用between
關鍵字,但我不確定如何實現這一更改,同時保留現有的邏輯。任何幫助是極大的讚賞。
Mysql或sql-server ....期待dbo。您正在使用sql-server ..請修復正確的標籤 –
糟糕。我的錯。謝謝。 – ic3man7019
我認爲你可以使用Dynamic Sql。只需組合查詢字符串。訪問此鏈接更多地提到,我的朋友:https://www.codeproject.com/Articles/20815/Building-Dynamic-SQL-In-a-Stored-Procedure – Tomato32