求日期所属星座的T-SQLUDF(用户自定义函数)


usenorthwind
go
CREATEFUNCTIONGetStar(@datetime)
RETURNSvarchar(100)
AS
BEGIN
--仅一句SQL搞定
RETURN
(
--declare@datetime
--set@=getdate()
selectmax(star)
from
(
--星座,该星座开始日期所属月,该星座开始日期所属日
select'魔羯座'asstar,1as[month],1as[day]
unionallselect'水瓶座',1,20
unionallselect'双鱼座',2,19
unionallselect'牧羊座',3,21
unionallselect'金牛座',4,20
unionallselect'双子座',5,21
unionallselect'巨蟹座',6,22
unionallselect'狮子座',7,23
unionallselect'处女座',8,23
unionallselect'天秤座',9,23
unionallselect'天蝎座',10,24
unionallselect'射手座',11,22
unionallselect'魔羯座',12,22
)stars
wheredateadd(day,[day]-1,dateadd(month,[month]-1,dateadd(year,datediff(year,0,@),0)))
=
(
selectmax(dateadd(day,[day]-1,dateadd(month,[month]-1,dateadd(year,datediff(year,0,@),0))))
from
(
select'魔羯座'asstar,1as[month],1as[day]
unionallselect'水瓶座',1,20
unionallselect'双鱼座',2,19
unionallselect'牧羊座',3,21
unionallselect'金牛座',4,20
unionallselect'双子座',5,21
unionallselect'巨蟹座',6,22
unionallselect'狮子座',7,23
unionallselect'处女座',8,23
unionallselect'天秤座',9,23
unionallselect'天蝎座',10,24
unionallselect'射手座',11,22
unionallselect'魔羯座',12,22
)stars
where@>=dateadd(day,[day]-1,dateadd(month,[month]-1,dateadd(year,datediff(year,0,@),0)))
)
)
end

go
--测试
usenorthwind
selectdbo.getstar(birthdate),count(*)
fromemployees
groupbydbo.getstar(birthdate)

你可能感兴趣的:(数据库,测试,sql)