存储过程返回多于1的值

时间:2014-03-24 13:40:54

标签: sql sql-server sql-server-2008

ALTER PROCEDURE [dbo].[sp_checktime]
( @Booking_Date date ,
    @Stime time(7) ,
    @Etime time(7) ,
    @Room varchar(50),
    @res int output
 )
AS
BEGIN
IF (@Stime=(select Start_Time from Booking_master where Booking_Date=@Booking_Date and Room=@Room) or @Stime>=(select Start_Time from Booking_master) and @Stime<=(select End_Time from Booking_master where Booking_Date=@Booking_Date and Room=@Room))
BEGIN
        set @res=0
END

ELSE    
    BEGIN
        set @res=1
    END

END

当激活此过程时,它会重新运行(子查询返回的值超过1。当子查询跟随=,!=,&lt;,&lt; =,&gt;,&gt; =或子查询被用作子查询时,不允许这样做一个表达。)

2 个答案:

答案 0 :(得分:2)

问题的直接原因是这句话:

@Stime=(select Start_Time from Booking_master where Booking_Date=@Booking_Date and Room=@Room)

子查询似乎返回多行。 “反身”修复方法是将其替换为in

@Stime in (select Start_Time from Booking_master where Booking_Date=@Booking_Date and Room=@Room)

在你的情况下,我认为你最好修复逻辑,这样你只有一个if (exists . . .)语句。类似的东西:

if (exists (select 1
            from Booking_master bm
            where Booking_Date = @Booking_Date and Room = @Room and
                  (@Stime = Start_Time or
                   (@Stime >= StartTime and @Stime <= EndTime)
                  )
           )
   )

答案 1 :(得分:0)

子查询只允许一个结果。尝试将TOP 1添加到每个子查询中,但问题很可能与第二个子查询隔离。

ALTER PROCEDURE [dbo].[sp_checktime]
( @Booking_Date date ,
    @Stime time(7) ,
    @Etime time(7) ,
    @Room varchar(50),
    @res int output
 )
AS
BEGIN
IF (
    @Stime = (select Top 1 Start_Time 
              from Booking_master 
              where Booking_Date=@Booking_Date and Room=@Room) 
 or @Stime >= (select Top 1 Start_Time 
               from Booking_master) 
and @Stime <= (select Top 1 End_Time 
               from Booking_master 
               where Booking_Date=@Booking_Date and Room=@Room))
BEGIN
        set @res=0
END

ELSE    
    BEGIN
        set @res=1
    END

END