我正在使用SQL Server 2005,我以dd-MM-yyyy
格式从用户获取日期,最多限制为5天,因此用户可以查看结果最多+ -5天。
我尝试了很多但无法:
dd-MM-yyyy
转换为yyyy-MM-dd
dd-MM-yyyy
我的SQL查询是:
SELECT
(convert(varchar(10), OrderDate, 105)) AS OrderDate
FROM
[Products] p
WHERE
((convert(varchar(10), OrderDate, 105)) BETWEEN
(DATEADD(dd, -3, '22-01-2014'))
AND
(DATEADD(dd, 3, '22-01-2014'))
)
在上述查询中,假设用户输入22-01-2014
作为日期,3输入flexibleDays
(因此用户可以看到19-01-2014至25-01-2014的结果)。
如何在上述SQL查询中添加格式dd-MM-yyyy
的天数?
答案 0 :(得分:1)
我建议 NOT 过度使用字符串的日期转换!如果您将DATE
或DATETIME
转换为字符串 - 当然您无法添加天数 - 毕竟它现在是一个字符串!
因此,如果您已经拥有一个DATE
或DATETIME
列 - 请使用它并保留其数据类型!
尝试使用以下代码:
-- define inputs from user - a date in string format, and a number of days
DECLARE @UserEntered VARCHAR(20) = '22-01-2014'
DECLARE @FlexiDays INT = 3
-- declare some helper variables - user input as DATE, from and to dates
DECLARE @UserEnteredDate DATE
DECLARE @FromDate DATE
DECLARE @ToDate DATE
-- determine the DATE the user entered, and the resulting "From" and "To" dates (as DATE)
SELECT @UserEnteredDate = CONVERT(DATE, @UserEntered, 105)
SET @FromDate = DATEADD(DAY, -1 * @FlexiDays, @UserEnteredDate)
SET @ToDate = DATEADD(DAY, @FlexiDays, @UserEnteredDate)
-- do your query without any messy conversions!
SELECT
OrderDate
FROM
[Products] p
WHERE
OrderDate BETWEEN @FromDate AND @ToDate
答案 1 :(得分:0)
尝试此功能
CREATE FUNCTION SUBTRACT_DAYS( @date AS DATETIME, @days AS INT )
RETURNS DATETIME
BEGIN
RETURN DATEADD(dd, -@days, @date);
END
CREATE FUNCTION ADD_DAYS(@date AS DATETIME, @days AS INT )
RETURNS DATETIME
BEGIN
RETURN DATEADD(dd, +@days, @date);
END
SELECT dbo.SUBTRACT_DAYS('2014-01-22', 3),dbo.ADD_DAYS('2014-01-22', 3)
<强> OP 强>
Start End
2014-01-19 00:00:00.000 2014-01-25 00:00:00.000
答案 2 :(得分:0)
试试这个:
DECLARE @UserEntered VARCHAR(20) = '22-01-2014'
DECLARE @FlexiDays INT = 3
DECLARE @UserEnteredDate DATE
DECLARE @FromDate DATE
DECLARE @ToDate DATE
dates (as DATE)
SELECT @UserEnteredDate = CONVERT(DATE, @UserEntered, 105)
SET @FromDate = DATEADD(DAY, -1 * @FlexiDays, @UserEnteredDate)
SET @ToDate = DATEADD(DAY, @FlexiDays, @UserEnteredDate)