简体   繁体   English

SQL:如何基于 GETDATE() 函数以 YYYYMM 格式获取上个月的整数值

[英]SQL: How to get an Integar value of the previous month in the format YYYYMM based on the GETDATE() Function

For example, if the todays date is 1/30/2019, I'd like to use the GETDATE() Function to return that date and set it equal to [Current_Date].例如,如果今天的日期是 1/30/2019,我想使用 GETDATE() 函数返回该日期并将其设置为等于 [Current_Date]。 I'd then like to use the current date to assign the value of 201912 to the variable @SETMONTH that I've declared as an Integar.然后,我想使用当前日期将 201912 的值分配给我已声明为 Integar 的变量 @SETMONTH。 Any help with code that is capable of doing this would be much appreciated.任何能够执行此操作的代码的帮助将不胜感激。

@SETMONTH INT

--To assign a value to [Current_Date]

SELECT 
    CONVERT(DATE, GETDATE()) [Current_Date]


UPDATE Table1

SET

Model_Month = --This is where I need a formula that can convert the date of 1/30/2020 to 201912

You can use EOMONTH() :您可以使用EOMONTH()

SELECT CONVERT(VARCHAR(6), EOMONTH(GETDATE(), -1), 112);

So, the update statement would looks like :所以,更新语句看起来像:

DECLARE @SETMONTH INT

SELECT @SETMONTH = CONVERT(VARCHAR(6), EOMONTH(GETDATE(), -1), 112)

UPDATE table1
      SET Model_Month = @SETMONTH

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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