How to subtract 30 days from the current date using SQL Server

后端 未结 4 1327
梦谈多话
梦谈多话 2020-12-09 01:07

I am unable subtract 30 days from the current date and I am a newbie to SQL Server.

This is the data in my column

date 
----------------------------         


        
相关标签:
4条回答
  • 2020-12-09 01:44

    You can convert it to datetime, and then use DATEADD(DAY, -30, date).

    See here.

    edit

    I suspect many people are finding this question because they want to substract from current date (as is the title of the question, but not what OP intended). The comment of munyul below answers that question more specifically. Since comments are considered ethereal (may be deleted at any given point), I'll repeat it here:

    DATEADD(DAY, -30, GETDATE())
    
    0 讨论(0)
  • 2020-12-09 01:44

    Try this:

    SELECT      GETDATE(), 'Today'
    UNION ALL
    SELECT      DATEADD(DAY,  10, GETDATE()), '10 Days Later'
    UNION ALL
    SELECT      DATEADD(DAY, –10, GETDATE()), '10 Days Earlier'
    UNION ALL
    SELECT      DATEADD(MONTH,  1, GETDATE()), 'Next Month'
    UNION ALL
    SELECT      DATEADD(MONTH, –1, GETDATE()), 'Previous Month'
    UNION ALL
    SELECT      DATEADD(YEAR,  1, GETDATE()), 'Next Year'
    UNION ALL
    SELECT      DATEADD(YEAR, –1, GETDATE()), 'Previous Year'
    

    Result Set:

    ———————– —————
    2011-05-20 21:11:42.390 Today
    2011-05-30 21:11:42.390 10 Days Later
    2011-05-10 21:11:42.390 10 Days Earlier
    2011-06-20 21:11:42.390 Next Month
    2011-04-20 21:11:42.390 Previous Month
    2012-05-20 21:11:42.390 Next Year
    2010-05-20 21:11:42.390 Previous Year
    
    0 讨论(0)
  • 2020-12-09 02:02

    TRY THIS:

    Cast your VARCHAR value to DATETIME and add -30 for subtraction. Also, In sql-server the format Fri, 14 Nov 2014 23:03:35 GMT was not converted to DATETIME. Try substring for it:

    SELECT DATEADD(dd, -30, 
           CAST(SUBSTRING ('Fri, 14 Nov 2014 23:03:35 GMT', 6, 21) 
           AS DATETIME))
    
    0 讨论(0)
  • 2020-12-09 02:04
    SELECT DATEADD(day,-30,date) AS before30d 
    FROM...
    

    But it is strongly recommended to keep date in datetime column, not varchar.

    0 讨论(0)
提交回复
热议问题