0

试图找出存储过程,我收到了这个错误:

消息 156,级别 15,状态 1,第 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
4

2 回答 2

1

创建过程 stmt 应该是批处理中的第一个。您不能在 try catch 块中执行此操作。除非你使用动态sql创建过程

于 2013-11-06T03:51:20.820 回答
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'')')
于 2013-11-06T06:15:56.770 回答