在SQL中获取当前年份的第一个月和第一天

时间:2022-12-05 20:24:33

I have a SP and I want to get the current year and the first day and first month of the year.

我有一个SP,我想要得到当前年,一年的第一天和第一个月。

For example, for this year : 2014-01-01; For 2015 : 2015-01-01;

例如,今年:2014-01-01;2015年:2015-01-01;

I tried

我试着

@data datetime , @test datetime

SELECT @test = GETDATE()
set @test = CAST( YEAR(@test)+'-'+'01'+'-'+'01' as char(100))
set @data = CAST( @test as datetime)

But it returns 2016 not 2014 any help?

但它将在2016年回归,而不是2014年回归,有什么帮助吗?

3 个解决方案

#1


5  

Your problem is that your are adding day and month to a numeric value. year() returns an integer.

您的问题是,您正在为数字值添加日和月。年()返回一个整数。

Implicit casting '-' as an int returns 0.

隐式铸造'-'作为一个int返回0。

So your expression would result in 2014+0+1+0+1 because when you have one integer and attempting to add (var)chars, sqlserver will attempt to convert everything else to integers.

因此,表达式将导致2014年+0+1+0+1,因为当您有一个整数并尝试添加(var)chars时,sqlserver将尝试将其他所有内容转换为整数。

The best way to manipulate the date to the first day of the year probably is this:

操纵日期到一年的第一天的最好方法可能是:

SELECT DATEADD(yy, DATEDIFF(yy, 0, getdate()), 0)

#2


0  

Here is a solution to get the result you want:

这里有一个方法可以得到你想要的结果:

DECLARE @test       DATETIME

SET @test = CAST(DATEPART(YEAR, GETDATE()) AS VARCHAR(4)) + '-01-01'

SELECT @test

The conversion to DATETIME is made automatically when you set the value.

当您设置值时,将自动转换到DATETIME。

Hope this will help you.

希望这能对你有所帮助。

#3


0  

you can just modify your snipped a little bit:

你可以稍微修改一下剪下来的部分:

declare @data datetime , @test datetime

SELECT @test = GETDATE()
set @test = convert(nvarchar(4),YEAR(@test)) +'-'+'01'+'-'+'01'
set @data = @test

this will work for you

这对你有用

#1


5  

Your problem is that your are adding day and month to a numeric value. year() returns an integer.

您的问题是,您正在为数字值添加日和月。年()返回一个整数。

Implicit casting '-' as an int returns 0.

隐式铸造'-'作为一个int返回0。

So your expression would result in 2014+0+1+0+1 because when you have one integer and attempting to add (var)chars, sqlserver will attempt to convert everything else to integers.

因此,表达式将导致2014年+0+1+0+1,因为当您有一个整数并尝试添加(var)chars时,sqlserver将尝试将其他所有内容转换为整数。

The best way to manipulate the date to the first day of the year probably is this:

操纵日期到一年的第一天的最好方法可能是:

SELECT DATEADD(yy, DATEDIFF(yy, 0, getdate()), 0)

#2


0  

Here is a solution to get the result you want:

这里有一个方法可以得到你想要的结果:

DECLARE @test       DATETIME

SET @test = CAST(DATEPART(YEAR, GETDATE()) AS VARCHAR(4)) + '-01-01'

SELECT @test

The conversion to DATETIME is made automatically when you set the value.

当您设置值时,将自动转换到DATETIME。

Hope this will help you.

希望这能对你有所帮助。

#3


0  

you can just modify your snipped a little bit:

你可以稍微修改一下剪下来的部分:

declare @data datetime , @test datetime

SELECT @test = GETDATE()
set @test = convert(nvarchar(4),YEAR(@test)) +'-'+'01'+'-'+'01'
set @data = @test

this will work for you

这对你有用