为什么这段代码会失败或不会失败?

问题描述:

编写它的最好方法是什么?因为我写了它,但我怀疑这不是一个好方法。为什么这段代码会失败或不会失败?

场景:我写这只是INSERTS记录到TABLE,然后拾取最后插入的主键,并返回到前端应用程序即

 @parameter1 int, 
     @Parameter2 smallint, 
     @Error varchar(MAX) output, 
     @OutPutParamter int Output 

Begin 
     Begin Try 
      insert into table1 
      values (@parameter1, @parameter2) 

      Set @OutPutParamter= Scope_Identity() 

     End Try 

     Begin Catch 
      set @Error= Select Error_Message() 
      set @OutPutParameter= 0 
     End Catch 
End 

现在的问题是,如何@OutPutParameter将被视为一个存储过程?回报价值有什么危害?

+0

我看不出有什么毛病你的程序。 – sgeddes

+0

我可以看到的主要危害是,当您尝试将'@OutPutParamter = 0'值放入任何具有'table1'外部属性的子表中时。 –

+0

@MotoGP我不这样做,这就是我在异常时返回的内容 – Stacky

  1. 你写的查询是正确的。
  2. Scope_Identity()将获得该记录插入到表
  3. @OutPutParamter是一个输出型变量,运行SP后的ID,你可以找到从@OutPutParamter的ID。
  4. 你也可以使用一个局部变量来获取ID和使用select返回值