开发者

SQL WHile Update with If conditions

I have the following query:

Declare @cnt as int
Declare @int as int
Set @int = 0
Select @cnt =COUNT(Date) FROM tmp
While @int < @cnt 
Begin


    If (Select Datepart(MM,Start_Time) from dbo.tmp)>='00' and (Select Datepart(MM,Start_Time) from dbo.tmp)<'15'
        Set tmp.Start_Int = Datepart(HH,Start_Time)+'00'

    else If (Select Datepart(MM,Start_Time) from dbo.tmp)>='15' and (Select Datepart(MM,Start_Time) from dbo.tmp)<'30'
        Set tmp.Start_Int = Datepart(HH,Start_Time)+'15'

    else If (Select Datepart(MM,Start_Time) from dbo.tmp)>='30' and (Select Datepart(MM,Start_Time) from dbo.tmp)<'45'
        Set tmp.Start_Int = Datepart(HH,Start_Time)+'30'

    else If (Select Datepart(MM,Start_Time) from dbo.tmp)>='45' and (Select Datepart(MM,Start_Time) from dbo.tmp)<='59'
        Set tmp.Start_Int = Datepart(HH,Start_Time)+'45'
    end

As you can see, I am trying to update Start_Int to its proper intervals depending on where it falls. Using this, I get an error saying Incorrect syntax near '.'. I can assume this query is incorrect, but I cannot find any examples of a while query that uses a sele开发者_如何学Cct to update a field if a condition is met.


The errors are thrown by the tmp.Start_Int declarations, which I think you are trying to insert values into a database table called tmp.

You need to change:

Set tmp.Start_Int = Datepart(HH,Start_Time)+'00'

to be something like:

update dbo.tmp set tmp.Start_Int = Datepart(HH,Start_Time)+'00' 

Also you might want to consider using a cursor to read through your data.

EDIT

Could you use the following as a basis?

declare @tmp table (Start_Time datetime)

insert into @tmp (Start_Time) values ('1-Oct-2011 21:02')
insert into @tmp (Start_Time) values ('1-Oct-2011 21:12')
insert into @tmp (Start_Time) values ('1-Oct-2011 21:22')
insert into @tmp (Start_Time) values ('1-Oct-2011 21:32')
insert into @tmp (Start_Time) values ('1-Oct-2011 21:42')
insert into @tmp (Start_Time) values ('1-Oct-2011 21:52')

select 
Start_Time, 
(case 
    when Datepart(MI,Start_Time) > 0 and datepart(MI, Start_Time) < 15 
        then cast(Datepart(HH,Start_Time) as varchar(5))+'00'
    when Datepart(MI,Start_Time) > 15 and datepart(MI, Start_Time) < 30 
            then cast(Datepart(HH,Start_Time) as varchar(5))+'15'
    when Datepart(MI,Start_Time) > 30 and datepart(MI, Start_Time) < 45 
            then cast(Datepart(HH,Start_Time) as varchar(5))+'30'
    when Datepart(MI,Start_Time) > 45  
            then cast(Datepart(HH,Start_Time) as varchar(5))+'45'
end) as Start_Int
from @tmp

Returns

Start_Time              Start_Int
----------------------- ---------
2011-10-01 21:02:00.000 2100
2011-10-01 21:12:00.000 2100
2011-10-01 21:22:00.000 2115
2011-10-01 21:32:00.000 2130
2011-10-01 21:42:00.000 2130
2011-10-01 21:52:00.000 2145
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜