2011-10-04 60 views
1

我有以下查詢:SQL同時更新與如果條件

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 

正如你所看到的,我想這取決於它落在更新Start_Int其適當的間隔。使用這個,我得到一個錯誤,說''附近的語法不正確。我可以假設這個查詢是不正確的,但我找不到任何一個while查詢的例子,如果條件滿足,它使用select來更新一個字段。

回答

2

錯誤是由tmp.Start_Int聲明引發的,我認爲您試圖將值插入到名爲tmp的數據庫表中。

你需要改變:

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

是這樣的:

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

而且你可能要考慮使用cursor通過你的數據讀取。

編輯

您可以使用以下作爲基礎?

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 

返回

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

Start_Int從表中可以dbo.tmp。我正在嘗試更新此字段,其中start_times符合if條件。 – Jessica

+1

然後你需要更新tmp表,而不是插入它。 – amelvin

+1

但是你還需要一個出你的while循環的方法,所以我想你在設置Start_Int值時需要做set @ cnt = @ cnt + 1。 – amelvin