简体   繁体   English

SQL Server:为前一个月设置两个变量,月份和年份,年份翻转安全

[英]SQL Server : setting two variables month and year for previous month, year roll over safe

I'm trying to basically dynamically set two variables (@month and @year) to be whatever the previous month and year were. 我试图基本上动态地设置两个变量(@month和@year)为上一个月和一年。

So in today's case @month = 7 and @year = 2012 所以在今天的情况下@month = 7@year = 2012

But I want something safe for the year roll around, so if it's 1/1/2013 I would get @month = 12 and @year = 2012 . 但是我希望在这一年中安全一些,所以如果是1/1/2013 1 @month = 12 ,我会得到@month = 12@year = 2012

Thanks! 谢谢!

This is what I have. 这就是我所拥有的。

declare @month              int
declare @year               int

set @month = month (getDate ())-1
set @year = 2012

You can use DATEADD to subtract a month from the current date, then grab the MONTH and YEAR portions: 您可以使用DATEADD从当前日期减去一个月,然后获取MONTHYEAR部分:

DECLARE @monthAgo dateTime
DECLARE @month int
DECLARE @year int

SET @monthAgo = DATEADD(month, -1, GETDATE())
SET @month = MONTH(@monthAgo)
SET @year = YEAR(@monthAgo)

Shown in steps. 分步显示。 You can modify the value assigned to @Now to test. 您可以修改分配给@Now的值以进行测试。

DECLARE @Now DateTime = GETDATE();
DECLARE @Then DateTime = DATEADD(Month, -1, @Now);

DECLARE @Month Int = DATEPART(Month, @Then);
DECLARE @Year Int = DATEPART(Year, @Then);

SELECT @Month, @Year;

As a single query, this gives the first day of last month: 作为一个查询,它给出了上个月的第一天:

select DATEADD(month,DATEDIFF(month,'20010101',CURRENT_TIMESTAMP),'20001201')

You can, if you choose, pull that apart into two separate variables, but why bother? 您可以选择将其分成两个单独的变量,但是为什么要麻烦呢? (I assume the rest of what you're doing is working with datetime s also, rather than int s) (我假设您正在做的其余事情也使用datetime ,而不是int


The two datetime strings above are selected because they have the desired relationship between them - that the second starts 1 month before the first. 选择上面的两个datetime字符串是因为它们之间具有所需的关系-第二个datetime字符串比第一个datetime时间早1个月。

can you not just add, after what you already have: 在已经拥有的内容之后,您是否可以不只是添加内容:

if @month = 0
begin
  set @month = 12
  set @year = @year - 1
end

Try this 尝试这个

declare @month int
declare @year int
Declare @dt datetime=getdate()
set @month = DATEPART(mm,DATEADD(mm,-1,@dt))
select @month
set @year = DATEPART(yy,DATEADD(mm,-1,@dt))
select @year

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

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