SP执行错误

时间:2011-05-16 14:14:02

标签: sql sql-server-2005

我在SP下面写。但是当我尝试运行此查询时,我收到此错误:

  

已经有一个名为的对象   数据库中的“#myCourses1”。

所以这会进入另外两个循环。还

create proc [dbo].[GetOrdersByUserIDwithSubscription]     
(    
    @UserID int    
)    
as    
begin    

    declare @status varchar(500)

    declare @substatus char(2)

    select @substatus=Subscribe_status from tbl_user where userid=@userid

    print @substatus

    if  @substatus='N'

    BEGIN    
        select a.*, b.CategoryText, Cast('' as Varchar(10)) as SectionsViewed, PurchasedDate as dateadded into #myCourses1 from dbo.Tbl_CourseInformations  a JOIN Tbl_Categories b ON a.AssignCategory = b.CategoryID    
        Join Tbl_Orders c ON c.UserID = @UserID and c.CourseID = a.CourseID  and c.courseprice<>'subscriber'  
        Order By CategoryText, CourseTitle         
    END  

    else if @substatus=''

    BEGIN    
        select a.*, b.CategoryText, Cast('' as Varchar(10)) as SectionsViewed, PurchasedDate as dateadded into #myCourses1 from dbo.Tbl_CourseInformations  a JOIN Tbl_Categories b ON a.AssignCategory = b.CategoryID    
        Join Tbl_Orders c ON c.UserID = @UserID and c.CourseID = a.CourseID and c.courseprice<>'subscriber'   
        Order By CategoryText, CourseTitle       
    END  

    else if @substatus='Y'    
    BEGIN    
        select a.*, b.CategoryText, Cast('' as Varchar(10)) as SectionsViewed, PurchasedDate as dateadded into #myCourses1 from dbo.Tbl_CourseInformations  a JOIN Tbl_Categories b ON a.AssignCategory = b.CategoryID    
        Join Tbl_Orders c ON c.UserID = @UserID and c.CourseID = a.CourseID    
        Order By CategoryText, CourseTitle 
    END 

4 个答案:

答案 0 :(得分:1)

此外,您所拥有的查询的怪异性可以简化为:

create proc [dbo].[GetOrdersByUserIDwithSubscription](    
    @UserID int    
)    
as    
begin
    declare @substatus char(2)

    select @substatus = Subscribe_status 
    from tbl_user 
    where userid = @userid

    select a.*, b.CategoryText, 
        Cast("" as Varchar(10)) as SectionsViewed, 
        PurchasedDate as dateadded 
    from dbo.Tbl_CourseInformations a 
        join Tbl_Categories b ON a.AssignCategory = b.CategoryID
        join Tbl_Orders c ON c.UserID = @UserID 
            and c.CourseID = a.CourseID 
            and (@substatus = 'N' or c.courseprice <> 'subscriber')
    order by CategoryText, CourseTitle         

END

答案 1 :(得分:1)

SQL Parser因为你在IF语句的不同部分使用了相同的临时表名而窒息。 IF没有其他编程语言的范围。

如果您不需要在每个IF块之外引用临时表,则可以通过在每个部分中使用不同的表名来解决问题。

查看my answer to a similar question

答案 2 :(得分:0)

您的语法是

SELECT [Column-List] INTO #TempTable FROM [Rest-of-Query]

使用此语法时,Sql Server会尝试根据列列表(source)动态创建#TempTable。

要解决此问题,请在存储过程开始时Drop #TempTable(如果您不需要超出SP范围的数据),或将其设为永久表。

答案 3 :(得分:0)

在proc开头显式创建临时表。

CREATE TABLE #myCourses1 (
    ...
)

然后将您的SELECT语句写为:

INSERT INTO #myCourses1
    select a.*, b.CategoryText, Cast('' as Varchar(10)) as SectionsViewed, PurchasedDate as dateadded 
        from dbo.Tbl_CourseInformations
        ...