# 如何获得当年的第一个和最后一个date

`01/01/2012``31/12/2012`

### 11 Solutions collect form web for “如何获得当年的第一个和最后一个date”

` `SELECT DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), 0) AS StartOfYear, DATEADD(yy, DATEDIFF(yy, 0, GETDATE()) + 1, -1) AS EndOfYear` `

` `SELECT DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), 0) AS StartOfYear, DATEADD(yy, DATEDIFF(yy, 0, GETDATE()) + 1, -1) AS LastDayOfYear, DATEADD(yy, DATEDIFF(yy, 0, GETDATE()) + 1, 0) AS FirstOfNextYear, DATEADD(ms, -3, DATEADD(yy, DATEDIFF(yy, 0, GETDATE()) + 1, 0)) AS LastTimeOfYear` `

` ` SELECT DATEADD(yy, DATEDIFF(yy, 0, '20150301'), 0) AS StartOfYearForMarch2015, DATEADD(yy, 2015 - 1900, 0) AS StartOfYearFor2015` `

` `SELECT '01/01/' + CONVERT(VARCHAR(4), DATEPART(yy, getUTCDate())), '31/12/' + CONVERT(VARCHAR(4), DATEPART(yy, getUTCDate()))` `

` ` SELECT '01/01/'+cast(year(getdate()) as varchar(4)) as [First Day], '12/31/'+cast(year(getdate()) as varchar(4)) as [Last Day]` `

` `select convert (date,DATEADD(YEAR,DATEDIFF(YEAR,0,GETDATE()),0))` `

` `select convert (date,DATEADD(YEAR, DATEDIFF(YEAR,0,GETDATE()) + 1, -1))` `

` `SELECT DATEADD(DD,-DATEPART(DY,GETDATE())+1,GETDATE())` `

` `SELECT DATEADD(DD,-1,DATEADD(YY,DATEDIFF(YY,0,GETDATE())+1,0))` `

` `select convert(varchar(12),(DateAdd(month,(Month(getdate())-1) * -1, DateAdd(Day,(Day(getdate())-1) * -1,getdate()))),103) as StartYear, convert(varchar(12),DateAdd(month,12 - Month(getdate()), DateAdd(Day,(31 - Day(getdate())),getdate())),103) as EndYear` `
` `select to_date(substr(sysdate,1, 4) || '01/01'), to_date(substr(sysdate,1, 4) || '12/31') from dual` `
` `SELECT DATEADD(DD,-DATEPART(DY,GETDATE())+1,GETDATE())` `
` `print Cast('1/1/' + cast(datepart(yyyy, getdate()) as nvarchar(4)) as date)` `

` `DATE_FORMAT(NOW(),'01/01/%Y') DATE_FORMAT(NOW(),'31/12/%Y')` `

— Lalmuni Demos —

` `create table Users ( userid int,date_of_birth date )` `

—插入值—

` `insert into Users values(4,'9/10/1991') select DATEDIFF(year,date_of_birth, getdate()) - (CASE WHEN (DATEADD(year, DATEDIFF(year,date_of_birth, getdate()),date_of_birth)) > getdate() THEN 1 ELSE 0 END) as Years, MONTH(getdate() - (DATEADD(year, DATEDIFF(year, date_of_birth, getdate()), date_of_birth))) - 1 as Months, DAY(getdate() - (DATEADD(year, DATEDIFF(year,date_of_birth, getdate()), date_of_birth))) - 1 as Days, from users` `
• 如何在TSQL Select中为每行生成随机数字？
• 创build表时声明一个默认约束
• 为数据库中所有存储过程的用户授予执行权限？
• 有没有办法让一个variables持续一段时间？
• 使用T-SQL查找最后一次出现子string的索引