DATE-DAY-yyyy格式的DATEADD

时间:2014-01-28 05:42:21

标签: c# asp.net sql sql-server-2005

我正在使用SQL Server 2005,我以dd-MM-yyyy格式从用户获取日期,最多限制为5天,因此用户可以查看结果最多+ -5天。

我尝试了很多但无法:

  1. dd-MM-yyyy转换为yyyy-MM-dd
  2. 在SQL查询中将日期添加到dd-MM-yyyy
  3. 我的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的天数?

3 个答案:

答案 0 :(得分:1)

我建议 NOT 过度使用字符串的日期转换!如果您将DATEDATETIME转换为字符串 - 当然您无法添加天数 - 毕竟它现在是一个字符串!

因此,如果您已经拥有一个DATEDATETIME列 - 请使用它并保留其数据类型!

尝试使用以下代码:

-- 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)