简体   繁体   English

sql获取年份和月份的日期

[英]sql get date with year and month

I have 2 variables in month and year, and I want to get the year value with these 2 variables. 我在月份和年份中有2个变量,并且我想通过这2个变量来获得年份值。 sample, year=2018 and month=5, i want '2018-05-01 00:00:000' Thanks for help. 示例,year = 2018和month = 5,我想要'2018-05-01 00:00:000'感谢您的帮助。

尝试这个

select cast(cast(year as varchar(max))+'-'+cast(month as varchar(max))+'-01' as datetime)

Try this .. you only have to format the date as 20180501 for SQL SERVER 试试这个..您只需要为SQL SERVER设置日期格式为20180501

declare @mm smallint = 5, @yy smallint = 2018

-- USING CONCAT -使用CONCAT

select cast(concat(cast(@yy as varchar(4)),right(concat('0',@mm),2),'01') as datetime)

--old concatenation method -旧的串联方法

select cast(cast(@yy as varchar(4))+right(concat('0',@mm),2)+'01' as datetime)

If SQL Server 2012 or higher you can use DATETIMEFROMPARTS 如果是SQL Server 2012或更高版本,则可以使用DATETIMEFROMPARTS

DECLARE @year INT = 2018
DECLARE @month INT = 5

SELECT DATETIMEFROMPARTS(@year, @month, 1, 0, 0, 0, 0)

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

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