简体   繁体   English

在SQL Server中更新日期时间的时间部分

[英]Update time portion of a datetime in SQL Server

I have a DateTime variable in SQL Server..I have the below code to check for weekend and then subtract the days to make it Friday. 我在SQL Server中有一个DateTime变量。我有以下代码来检查周末,然后减去使之成为星期五的天数。 Now I also want to set the time of this new Datetime as 5 PM on the Friday. 现在我也想将这个新的日期时间设置为星期五的下午5点。 Can someone please tell me how can I achieve this. 有人可以告诉我如何实现这一目标。

if(DATENAME(DW, @EndDate) = 'Sunday')
Begin
Set @EndDate = (SELECT DATEADD(DAY, -2, @EndDate))
End
if(DATENAME(DW, @EndDate) = 'Saturday')
Begin
Set @EndDate = (SELECT DATEADD(DAY, -1, @EndDate))
End
End

Thanks 谢谢

You can add 17 hours: 您可以增加17小时:

Set @EndDate = DATEADD(HOUR, 17, DATEADD(DAY, -1, @EndDate))

I have no idea why you have phrased this logic using a subquery. 我不知道您为什么使用子查询来表达这种逻辑。 It is not necessary. 没有必要。

If your data already has a time component, then cast to a date first to get rid of the time component, then back to a datetime : 如果您的数据已经具有时间成分,则首先强制转换为date以摆脱时间成分,然后转换为datetime

Set @EndDate = DATEADD(HOUR, 17, DATEADD(DAY, -1, CONVERT(datetime, CONVERT(DATE, @EndDate))))

选择演员表(CONVERT(varchar(12),GETDATE())+ '17:00'作为日期时间)

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

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