存储过程,'语法错误'

时间:2013-11-06 03:47:47

标签: sql sql-server stored-procedures

试图弄清楚存储过程,我收到了这个错误:

  

Msg 156,Level 15,State 1,Line 5
  关键字“过程”附近的语法不正确。

错误似乎在if上,但是我可以使用存储过程以完全相同的方式删除其他现有表,因此我不清楚为什么这不起作用。任何人都能解释一下吗?

Begin
Set nocount on 
Begin Try

    Create Procedure uspRecycle
    as
        if OBJECT_ID('Recycle') is not null
            Drop Table Recycle

        create table Recycle
            (RecycleID integer
                constraint PK_integer primary key,
            RecycleType nchar(10) not null,
            RecycleDescription nvarchar(100) null)

            insert into Recycle
                (RecycleID,RecycleType,RecycleDescription)
            values ('1','Compost','Product is compostable, instructions included in packaging')
            insert into Recycle
                (RecycleID,RecycleType,RecycleDescription)
            values ('2','Return','Product is returnable to company for 100% reuse')
            insert into Recycle
                (RecycleID,RecycleType,RecycleDescription)
            values ('3','Scrap','Product is returnable and will be reclaimed and reprocessed')
            insert into Recycle
                (RecycleID,RecycleType,RecycleDescription)
            values ('4','None','Product is not recycleable')



End Try

Begin Catch
  DECLARE @ErrMsg nvarchar(4000);
  SELECT @ErrMsg = ERROR_MESSAGE();
  Throw 50001, @ErrMsg, 1;
End Catch

-- checking to see if table exists and is loaded:
If (Select count(*) from Recycle) >1 
    begin
        Print 'Recycle table created and loaded '; Print getdate()
    End
set nocount off 
End

2 个答案:

答案 0 :(得分:1)

创建过程stmt应首先批量生效。你不能在try catch块中做到这一点。除非您使用动态sql创建过程

答案 1 :(得分:0)

你也可以在你的创建过程语句周围放一个exec('...')......就像这样:

exec('Create Procedure uspRecycle
as
    if OBJECT_ID(''Recycle'') is not null
        Drop Table Recycle

    create table Recycle
        (RecycleID integer
            constraint PK_integer primary key,
        RecycleType nchar(10) not null,
        RecycleDescription nvarchar(100) null)

        insert into Recycle
            (RecycleID,RecycleType,RecycleDescription)
        values (''1'',''Compost'',''Product is compostable, instructions included in packaging'')
        insert into Recycle
            (RecycleID,RecycleType,RecycleDescription)
        values (''2'',''Return'',''Product is returnable to company for 100% reuse'')
        insert into Recycle
            (RecycleID,RecycleType,RecycleDescription)
        values (''3'',''Scrap'',''Product is returnable and will be reclaimed and reprocessed'')
        insert into Recycle
            (RecycleID,RecycleType,RecycleDescription)
        values (''4'',''None'',''Product is not recycleable'')')