2016-01-12 82 views
-1

我有表LessonHour,列爲空Number如何填寫基於其他兩列的列

TABLE [dbo].[LessonHour] 
(
    [Id] [uniqueidentifier] NOT NULL, 
    [StartTime] [time](7) NOT NULL, 
    [EndTime] [time](7) NOT NULL, 
    [SchoolId] [uniqueidentifier] NOT NULL, 
    [Number] [int] NULL 
) 

我怎樣才能填補了Number表每個LessonHour所以會課時間的數量,以便? LessonHours不能相互交叉。每所學校都制定了自己的課時模式。

示例設置數據 http://pastebin.com/efWCtUbv

什麼了我做的:

  1. 訂購SchoolId和開始時間
  2. 使用光標插入到行下一個數字,從1每次啓動SchoolId變化。

編輯:

解決方案與光標

select -- top 20 
     LH.[Id], 
     [StartTime], 
     [EndTime], 
     [SchoolId] 
into #LH 
from 
    LessonHour as LH 
    join RowStatus as RS on LH.RowStatusId = RS.Id 
where 
    RS.IsActive = 1 

select * from #LH order by SchoolId, StartTime 

declare @id uniqueidentifier, @st time(7), @et time(7), @sid uniqueidentifier 
declare @prev_sid uniqueidentifier = NEWID() 
declare @i int = 1 
declare cur scroll cursor for 
select * from #LH order by SchoolId, StartTime 
open cur; 
fetch next from cur into @id, @st, @et, @sid 
while @@FETCH_STATUS = 0 
begin 
    --print @prev_sid 
    if @sid <> @prev_sid 
    begin 
     set @i = 1 
    end 

    update LessonHour set Number = @i where Id = @id 

    print @i 
    set @i = @i + 1 

    set @prev_sid = @sid 
    fetch next from cur into @id, @st, @et, @sid 
end; 
close cur; 
deallocate cur; 

drop table #LH 

這是我的結果後http://pastebin.com/iZ8cnA6w

+0

你有一個問題,你有一個想法如何解決這個問題。但你的問題是什麼?您是否實施並測試了您的解決方案?你是否遇到過任何問題,或者你想知道是否有更好的方法來做到這一點? –

+2

非常不清楚,但讓我們試着用'ROW_NUMBER()'** [demo ....҉](https://data.stackexchange.com/stackoverflow/query/422677)** – lad2025

+0

@WernerHenze我在找更好的解決方案。我不喜歡使用光標,但我不知道如何以任何其他方式做到這一點。 – pizycki

回答

-1

將這工作

CREATE TABLE [dbo].[LessonHour] 
(
    [Id] [uniqueidentifier] NOT NULL, 
    [StartTime] [time](7) NOT NULL, 
    [EndTime] [time](7) NOT NULL, 
    [SchoolId] [uniqueidentifier] NOT NULL, 
    [Number] AS DATEDIFF(hour,[StartTime],[EndTime]) 
) 

因此,如果我正確理解問題,則需要一個計算列,其中包含[StartTime]和[EndTime]的值,並將該課程的小時數作爲int返回。上面的表格定義應該做到這一點。

enter image description here

+0

不需要。我需要爲每所學校編課時數。 – pizycki

+0

這個怎麼樣! –

+0

運行'UPDATE [dbo]。[LessonHour] SET [Number] = DATEDIFF(hour,[StartTime],[EndTime])'我得到這個http://pastebin.com/tKRFp4h3 – pizycki