在这个存储过程中,在where条件中,如果@startDate和@EndDate值为null,那么如何使用COALESCE来处理它。
CREATE PROCEDURE dbo.SP_ManageLeaveSearch
@StartDate datetime,
@EndDate datetime,
@UserName CHAR(100),
@MarketID INT
AS
BEGIN
SELECT d1.UserName,c1.HouseName,c.StartDate,c.EndDate
FROM table1 c
Inner JOIN table2 d1 ON c.UserID = d1.UserID
WHERE
(
(
(@StartDate BETWEEN StartDate AND EndDate)
OR
(@EndDate BETWEEN StartDate AND EndDate)
OR
(
(@StartDate <= Startdate AND @EndDate>=EndDate)
)
)
AND
(
d1.UserName = COALESCE(@UserName, d1.UserName)
)
)
END
提前做好准备。
答案 0 :(得分:4)
这应该适合你:
CREATE PROCEDURE dbo.ManageLeaveSearch
@StartDate datetime = NULL,
@EndDate datetime = NULL,
@UserName CHAR(100) = NULL,
@MarketID INT
AS
BEGIN
SELECT d1.UserName,c1.HouseName,c.StartDate,c.EndDate
FROM table1 c
Inner JOIN table2 d1 ON c.UserID = d1.UserID
WHERE
COALESCE(@StartDate,StartDate) <= EndDate AND
StartDate <= COALESCE(@EndDate,EndDate) AND
d1.UserName = COALESCE(@UserName, d1.UserName)
END
注意:
sp_
前缀命名存储过程 - 它是为Microsoft system procedures保留的。答案 1 :(得分:1)
试试这个 -
CREATE PROCEDURE dbo.usp_ManageLeaveSearch
@StartDate DATETIME,
@EndDate DATETIME,
@UserName CHAR(100),
@MarketID INT
AS BEGIN
SELECT
d1.UserName
, c.HouseName
, c.StartDate
, c.EndDate
FROM dbo.table1 c
JOIN dbo.table2 d1 ON c.UserID = d1.UserID
WHERE d1.UserName = ISNULL(@UserName, d1.UserName)
AND (
ISNULL(@StartDate, StartDate) BETWEEN StartDate AND EndDate
OR
ISNULL(@EndDate, EndDate) BETWEEN StartDate AND EndDate
)
END
答案 2 :(得分:1)
你的事情过于复杂。这应该对你有用,并且就像我所知的那样简单。我更喜欢这种语法,因为在我的大多数用例中,...或@UserName IS NULL可以在查询执行之前从查询中删除,从而实现非常简单,快速的执行。
CREATE PROCEDURE dbo.SP_ManageLeaveSearch
@StartDate datetime,
@EndDate datetime,
@UserName CHAR(100),
@MarketID INT
AS
BEGIN
SELECT d1.UserName,c1.HouseName,c.StartDate,c.EndDate
FROM table1 c
JOIN table2 d1
ON c.UserID = d1.UserID
WHERE (@StartDate<=EndDate OR @StartDate IS NULL)
AND (@EndDate>=StartDate OR @EndDate IS NULL)
AND (d1.UserName = @UserName OR @UserName IS NULL)
END