while循环填充表格

时间:2016-11-22 14:31:31

标签: sql-server tsql

我正在尝试使用while循环来填充SQL Server中的表。从星期一到星期五的上午8:00到下午7:00,数据将以5分钟为增量。

以下是我尝试将变量@Beg传递给@Temp时的代码我收到错误:

  

Msg 102,Level 15,State 1,Line 85
  ' @ Temp'。

附近的语法不正确      

Msg 102,Level 15,State 1,Line 90
  ' @ Beg'附近的语法不正确。

我的代码:

Create Table TIMESLOT
(
    TIMESLOTID  int not null identity(1,1),
    Beg_Time    datetime not null,
    End_Time    datetime not null,
    TimeDayOFWeek   varChar(25) not null
);

DECLARE @Beg as Time;
DECLARE @Temp as Time;
DECLARE @End as Time;
DECLARE @Day as dayofweek;

set @Beg = '08:00 AM';
Set @End = '07:00 PM';
set @Day = 'Monday';

While (@Day != 'Saturday' )
Begin
    While (@Beg <= @End)
    Begin
        @Temp = @Beg;

        DateAdd(minute,5,@Temp)

        Insert into TIMESLOT (Beg_Time, End_Time, TimeDay0fWeek) 
        Values (@Beg, @Temp, @Day)

        if (@Beg <= @End)
            @Beg = @Temp
        Else
            @Beg = '08:00 AM'
            @Day = Datadd(day, 1, @Day)
        End
    End
End

2 个答案:

答案 0 :(得分:1)

尝试以下方法。你的语法不太正确

Create Table TIMESLOT
(
    TIMESLOTID  int not null identity(1,1),
    Beg_Time    datetime not null,
    End_Time    datetime not null,
    TimeDayOFWeek   varChar(25) not null
);

DECLARE @Beg as Time;
DECLARE @Temp as Time;
DECLARE @End as Time;
DECLARE @Day as dayofweek;

set @Beg = '08:00 AM';
Set @End = '07:00 PM';
set @Day = 'Monday';

While (@Day != 'Saturday' )
Begin
    While (@Beg <= @End)
    Begin
        Set @Temp = @Beg;
        Set @Temp = DateAdd(MINUTE,5,@Temp)
        Insert into TIMESLOT (Beg_Time, End_Time, TimeDayOFWeek) 
        Values (@Beg, @Temp, @Day)
        If (@Beg <= @End)
        Begin
            Set @Beg = @Temp
        End
        Else
        Begin
            Set @Beg = '08:00 AM'
            Set @Day = DateAdd(day,1, @Day)
        End
    End
End

答案 1 :(得分:0)

这是最终修复问题的代码,Wheels73是正确的,我的语法错误。但是我也把if语句和变量@beg重置在错误的区域。

While (@Day != 'Saturday' ) -- first end
Begin
    While (@Beg < @End)
    Begin--Second
        Set @Temp = @Beg
        Set @Temp = DateAdd(MINUTE,5,@Temp)
        Insert into TIMESLOT (Beg_Time, End_Time, TimeDayOFWeek) 
        Values (@Beg, @Temp, @Day)
        Set @Beg = @Temp
    End--Second
    Set @Beg = '08:00 AM'
    if(@Day = 'Monday')
        Begin
            Set @Day = 'Tuesday'
        End
    Else if(@Day = 'Tuesday')
        Begin
            Set @Day = 'Wednesday'
        End
    Else if (@Day = 'Wednesday')
        Begin
            Set @Day = 'Thursday'
        End
    Else if (@Day = 'Thursday')
        Begin
            Set @Day = 'Friday'
        End 
    Else 
        Begin
            Set @Day = 'Saturday'
        End
End--firstenter code here