[英]how to use for each loop in sql server?
I have a table tblEmpDetail
which contains a column CreatedDate
. 我有一个表
tblEmpDetail
,其中包含一列CreatedDate
。
I want to add 72 hours to each created date, so if the created date is 2012-07-14 07:21:19.180
then I want the output to be 2012-07-17 07:21:19.180
. 我想为每个创建的日期添加72小时 ,所以如果创建的日期为
2012-07-14 07:21:19.180
那么我希望输出为2012-07-17 07:21:19.180
。
Can someone let me know how can I accomplish to this? 有人可以告诉我如何做到这一点吗?
Actually what I want to do is to go to each row then check if the 实际上,我要执行的操作是转到每一行,然后检查
getdate() - createddate
is equal to or less than 72 hours; 等于或少于72小时; then I need to add 72 hours to
createddate
. 然后我需要添加72小时到
createddate
。 Otherwise I want that column to be null. 否则,我希望该列为空。 I am pasting my code that what I have done.
我正在粘贴我所做的代码。
Declare @PassedTime datetime
set @PassedTime= DATEDIFF(HH,Createddate, GETDATE())
if CONVERT(varchar(20),@PassedTime,108)>=CONVERT(varchar(20),'72:00:00',108)
begin
select empno,empName,CreatedDate,dateadd(HH,72,CreatedDate)BD from tblEmpDetail
end
else
begin
select empno,empName,CreatedDate,'' as BD from tblEmpDetail
end
No looping is required. 无需循环。
SQL Server excels at doing "set based" queries. SQL Server擅长执行“基于集合”的查询。
To get a projection: 获取投影:
select
CreatedDate,
DateAdd(hour, 72, CreatedDate) [NewDate]
from
tblEmpDetail
To update the table permanently: 永久更新表:
update
tblEmpDetail
set
CreatedDate = DateAdd(hour, 72, CreatedDate)
If you MUST have a loop, you can use a cursor: 如果必须循环,则可以使用游标:
declare cur cursor fast_forward read_only for
select
CreatedDate,
DateAdd(hour, 72, CreatedDate) [NewDate]
from
tblEmpDetail
-- here, you would use the cursor.
More information on cursors here: http://msdn.microsoft.com/en-us/library/ms180169.aspx 有关游标的更多信息,请参见: http : //msdn.microsoft.com/zh-cn/library/ms180169.aspx
Your query above can be done in a set based way like this: 您上面的查询可以通过以下基于集合的方式完成:
select
CreatedDate,
CASE
WHEN DateAdd(hour, 72, CreatedDate) <= GetDate() THEN NULL
ELSE DateAdd(hour, 72, CreatedDate)
END [NewDate]
from
tblEmpDetail
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.