我有这个存储过程:
ALTER PROCEDURE [dbo].[GetCalendarEvents]
(@StartDate datetime,
@EndDate datetime,
@Location varchar(250) = null)
AS
BEGIN
SELECT *
FROM Events
WHERE EventDate >= @StartDate
AND EventDate <= @EndDate
AND (Location IS NULL OR Location = @Location)
END
现在,我有location参数,我想要做的是如果参数不为null,那么在where子句中包含参数。如果参数为null,我想完全忽略where参数,只能通过开始和结束日期获得结果。
因为当我这样做时:
EXEC GetCalendarEvents '02/02/2014', '10/10/2015', null
我没有得到任何结果,因为有其他位置不为null,并且由于location参数为null,我想从所有位置获取结果。
我知道如何解决这个问题?
谢谢,Laziale
答案 0 :(得分:2)
ALTER PROCEDURE [dbo].[GetCalendarEvents]
( @StartDate DATETIME,
@EndDate DATETIME,
@Location VARCHAR(250) = NULL
)
AS
BEGIN
SELECT *
FROM events
WHERE EventDate >= @StartDate
AND EventDate <= @EndDate
AND Location = ISNULL(@Location, Location )
END
如果有可能是NULL列,那么这将有效。
ALTER PROCEDURE [dbo].[GetCalendarEvents]
( @StartDate DATETIME,
@EndDate DATETIME,
@Location VARCHAR(250) = NULL
)
AS
BEGIN
IF ( @loc IS NULL )
BEGIN
SELECT *
FROM events
WHERE EventDate >= @StartDate
AND EventDate <= @EndDate
END
ELSE
BEGIN
SELECT *
FROM events
WHERE EventDate >= @StartDate
AND EventDate <= @EndDate
AND Location = @Location
END
END
有一个&#39; OR&#39;由于可能存在性能问题,应合理避免使用该条款。
答案 1 :(得分:0)
然后应该阅读WHERE
子句中的部分
AND (@Location IS NULL OR Location=@Location)
答案 2 :(得分:0)
试试这个
SELECT *
FROM Events
WHERE EventDate >= @StartDate
AND EventDate <= @EndDate
AND Location = Case When LEN(@Location) > 0 Then @Location Else Location End
答案 3 :(得分:0)
可以使用动态SQL查询轻松完成。
ALTER PROCEDURE [dbo].[GetCalendarEvents]
(@StartDate datetime,
@EndDate datetime,
@Location varchar(250) = null)
AS
BEGIN
DECLARE @SQL NVARCHAR(MAX);
DECLARE @PARAMETER_DEFIINITION NVARCHAR(MAX);
DECLARE @WHERE_PART NVARCHAR(MAX);
SET @PARAMETER_DEFIINITION =' @StartDate DATETIME, @EndDate DATETIME, @Location VARCHAR(250) '
SET @SQL ='SELECT *
FROM Events
WHERE EventDate >= @StartDate
AND EventDate <= @EndDate '
IF @Location IS NOT NULL
BEGIN
SET @WHERE_PART = ' AND Location = @Location '
END
SET @SQL = @SQL + @WHERE_PART
EXEC SP_EXECUTESQL @SQL, @PARAMETER_DEFIINITION, @StartDate, @EndDate, @Location
END
将根据参数动态创建查询。在这里,如果@location为null,那么它将不会添加到where部分。
如果您想要更多编写动态查询,请参阅此文章。 http://codingpulse.blogspot.com/2015/02/dynamic-sql-in-stored-procedure-part-1.html