简体   繁体   中英

Set Static Day and Previous Month GETDATE() SQL

The following SQL statement sets the date for a particular column:

DATEDUE=convert(varchar,GETDATE(),103 )

However, its sets the current date such as 05/08/2015. What I wish to do is to have it in the same dd/mm/yyyy format but to set the day to the 15th and the month to the previous month, so 05/08/2015 should be 15/07/2015 instead.

select CONVERT(VARCHAR(10),
              DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE())-1, 0) + 14
              ,103)

 Result: 15/07/2015

Important Note

Since DATEDUE column is storing dates, you should really use the sql server DATE data type for storing date values in that column.

if you decide you just need the most recent previous 15th of the month you can use this.

SELECT CONVERT(VARCHAR(10),
       DATEADD(DAY,14,DATEADD(MONTH,DATEDIFF(MONTH,0,GETDATE()) - 
       (CASE WHEN DATEPART(DAY,GETDATE()) > 15 THEN 0 ELSE 1 END), 0)),
       103)

05/08/2015 becomes 15/07/2015 and 24/08/2015 becomes 15/08/2015 instead of 15/07/2015

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM