[MSSQL]根据日期返回星座

本文介绍了一个使用SQL编写的函数,该函数可以根据输入的日期参数返回对应的星座名称。通过复杂的日期比较逻辑,确保了星座判断的准确性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

go --创建函数(优快云 fredrickhu(小F)提供) create function udf_GetStar (@ datetime) RETURNS varchar(100) -- 返回日期所属星座 BEGIN RETURN ( select max(star) from ( select '魔羯座' as star,1 as [month],1 as [day] union all select '水瓶座',1,20 union all select '双鱼座',2,19 union all select '牡羊座',3,21 union all select '金牛座',4,20 union all select '双子座',5,21 union all select '巨蟹座',6,22 union all select '狮子座',7,23 union all select '处女座',8,23 union all select '天秤座',9,23 union all select '天蝎座',10,24 union all select '射手座',11,22 union all select '魔羯座',12,22 ) stars where dateadd(month,[month] - 1,dateadd(year,year(@) - year(0),0)) + [day] - 1 = ( select max(dateadd(month,[month] - 1,dateadd(year,year(@) - year(0),0)) + [day] - 1) from ( select '魔羯座' as star,1 as [month],1 as [day] union all select '水瓶座',1,20 union all select '双鱼座',2,19 union all select '牡羊座',3,21 union all select '金牛座',4,20 union all select '双子座',5,21 union all select '巨蟹座',6,22 union all select '狮子座',7,23 union all select '处女座',8,23 union all select '天秤座',9,23 union all select '天蝎座',10,24 union all select '射手座',11,22 union all select '魔羯座',12,22 ) stars where @ >= dateadd(month,[month] - 1,dateadd(year,year(@) - year(0),0)) + [day] - 1 ) ) end --测试示例 select dbo.udf_GetStar('2010-05-04') select dbo.udf_GetStar('2009-01-04') select dbo.udf_GetStar('2007-12-04') --运行结果 /* 金牛座 魔羯座 射手座 */
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值