我想要做的是从sql获取结果,其中日期在一定范围内,但它不能正常工作,这是我的查询.
DECLARE @CurrDate DATETIME
SET @CurrDate = GETDATE()
SELECT dbo.ProductDetails.PartnerID
,dbo.ProductDetails.ProductID
,dbo.Products.ProductName
,StartDate
,EndDate
FROM dbo.ProductDetails
INNER JOIN dbo.Products
ON dbo.ProductDetails.ProductID = dbo.Products.ProductID
WHERE CONVERT(VARCHAR(10),StartDate,111) <= @CurrDate
AND CONVERT(VARCHAR(10),EndDate, 111) >= @CurrDate
Run Code Online (Sandbox Code Playgroud)
但是当该Enddate = @CurrDate行没有显示时,如果我将该日期提高一天,则会显示该日期.我做错了吗?任何建议都可以,谢谢.
GetDate()返回日期和时间,而你转换为varchar去除了时间部分(我怀疑这是它实际应该做的全部).所以你需要做同样的转换@CurrDate.
如果你想要的只是简单地考虑日期(忽略时间部分),你可以使用DATEDIFF而不是转换为varchar(见这里); 例:
DECLARE @CurrDate DATETIME
SET @CurrDate = GETDATE()
SELECT dbo.ProductDetails.PartnerID, dbo.ProductDetails.ProductID,
dbo.Products.ProductName , StartDate, EndDate
FROM dbo.ProductDetails INNER JOIN
dbo.Products ON dbo.ProductDetails.ProductID = dbo.Products.ProductID
-- where StartDate is on the same day or before CurrDate:
WHERE DATEDIFF(day, StartDate, @CurrDate) >= 0 AND
-- and where EndDate is on the same day or after CurrDate:
DATEDIFF(day, EndDate, @CurrDate) <= 0
Run Code Online (Sandbox Code Playgroud)