我正在編寫一個關於基於aspx頁面文本框輸入文本搜索數據庫的存儲過程。如何在參數爲空或空時忽略或忽略where子句
此存儲過程運行良好,但我有一個問題。
有時@DeptName
和@DutyName
參數爲空或空。
所以我想跳過或忽略where參數值爲空時的子句。但我對如何處理這種情況感到困惑。
請給我你的意見。
我的存儲過程的代碼:
DECLARE
@CompanyCode varchar(20)
, @DeptName nvarchar(20)
, @DutyName nvarchar(20)
SELECT
@CompanyCode = 'h101'
, @DeptName = 'IT'
, @DutyName = 'Manager'
SELECT
U.ADDisplayName AS UserName
, LOWER(U.UserID) AS EmpID
, ISNULL(CPN.CompanyName, '') AS CompanyCode
, ISNULL(U.DisplayName_Eng, '') AS DisplayName_Eng
, ISNULL(DT.DisplayName, '') AS DeptName
, ISNULL(DTY.DutyName, '') AS DutyName
, ISNULL(U.CellPhone, '') AS CellPhone
, ISNULL(U.ExtensionNumber, '') AS ExtensionNumber
, ISNULL(U.FaxNumber, '') AS FaxNumber
, ISNULL(U.ChargeJob, '') AS ChargeJob
, ISNULL(LOC.LocationName, '') AS LocationName
, ISNULL(U.Workplace, '') AS Workplace
, ISNULL(U.EMail, '') AS EMail
FROM dbo.tb_User U
INNER JOIN dbo.tb_Dept DT
ON U.MainDeptCode = DT.DeptCode
INNER JOIN dbo.tb_Company CPN
ON U.CompanyCode = CPN.CompanyCode
INNER JOIN dbo.tb_Location LOC
ON U.LocationCode = LOC.LocationCode
AND U.CompanyCode = LOC.CompanyCode
AND U.GroupCode = LOC.GroupCode
AND U.DetailCode = loc.DetailCode
INNER JOIN dbo.tb_Duty DTY
ON U.DutyCode = DTY.DutyCode
AND U.CompanyCode = DTY.CompanyCode
AND U.GroupCode = DTY.GroupCode
AND U.DetailCode = DTY.DetailCode
WHERE U.CompanyCode = @companyCode
AND DT.DisplayName like '%' + @DeptName + '%'
AND DTY.DutyName like '%' + @DutyName + '%'
Order by DeptName desc
謝謝。
請採取[ISNULL檢查]一看(https://stackoverflow.com/questions/4224991/sql-server-checking-an-input-param-if-not-null-and-using-它功能於其中) – OnDoubt