SQL查询日期空检查
我有以下存储过程SQL查询日期空检查,sql,Sql,我有以下存储过程 ALTER PROCEDURE [dbo].[spList_Report] @id INT, @startDate DATETIME = NULL, @endDate DATETIME = NULL, @includeStatus1 BIT, @includeStatus2 BIT, @includeStatus3 BIT, @includeStatus4 BIT AS SET NOCOUNT ON SELECT *
ALTER PROCEDURE [dbo].[spList_Report]
@id INT,
@startDate DATETIME = NULL,
@endDate DATETIME = NULL,
@includeStatus1 BIT,
@includeStatus2 BIT,
@includeStatus3 BIT,
@includeStatus4 BIT
AS
SET NOCOUNT ON
SELECT *
FROM
tblProducts as products
WHERE
product.intID = @id
AND product.dateMain >= @startDate
AND product.dateMain <= @endDate
ALTER过程[dbo]。[spList\u报告]
@id INT,
@startDate DATETIME=NULL,
@endDate DATETIME=NULL,
@包括状态1位,
@包括状态2位,
@包括状态3位,
@includeStatus 4位
作为
不计较
选择*
从…起
TBL产品作为产品
哪里
product.intID=@id
和product.dateMain>=@startDate
和product.dateMain这样就可以了
AND product.dateMain >= ISNULL( @startDate, 0)
AND product.dateMain <= ISNULL( @endDate, product.dateMain + 1)
和product.dateMain>=ISNULL(@startDate,0)
还有product.dateMain你可以试试这样的东西
ALTER PROCEDURE [dbo].[spList_Report]
@id INT,
@startDate DATETIME = NULL,
@endDate DATETIME = NULL,
@includeStatus1 BIT,
@includeStatus2 BIT,
@includeStatus3 BIT,
@includeStatus4 BIT
AS
SET NOCOUNT ON
SELECT *
FROM
tblProducts as products
WHERE
product.intID = @id
AND product.dateMain >= ISNULL( @startDate, product.dateMain )
AND product.dateMain <= ISNULL( @endDate, product.dateMain )
ALTER过程[dbo]。[spList\u报告]
@id INT,
@startDate DATETIME=NULL,
@endDate DATETIME=NULL,
@包括状态1位,
@包括状态2位,
@包括状态3位,
@includeStatus 4位
作为
不计较
选择*
从…起
TBL产品作为产品
哪里
product.intID=@id
并且product.dateMain>=ISNULL(@startDate,product.dateMain)
和product.dateMain您可以在Sql中使用“或”,但由于这是一个存储过程:
If @startdate is null Or @enddate is null
begin
select without using a date range
end
Else
begin
select using date range
end
我会使用Kris Krause的解决方案,但将“IF”语句改为“AND”。我认为如果使用前两种解决方案,查询引擎可能会对日期字段执行表/索引扫描。为了获得最佳性能,您希望使查询尽可能简洁,因此不要在不必要的列上运行查询
IF @startdate IS NULL AND @enddate IS NULL
BEGIN
SELECT * FROM tblProducts as products WHERE
product.intID = @id
END
ELSE
BEGIN
SELECT * FROM tblProducts as products WHERE
product.intID = @id
AND product.dateMain >= @startDate
AND product.dateMain <= @endDate
END
如果@startdate为空且@enddate为空
开始
从TBL产品中选择*作为产品,其中
product.intID=@id
结束
其他的
开始
从TBL产品中选择*作为产品,其中
product.intID=@id
和product.dateMain>=@startDate
还有product.dateMain这是一个很大的重复,不过,对于一些有更简单解决方案的东西(Lieven、IordanTanev和我都得到了相同的解决方案)