使用OUTPUT子句的SQL过程不返回值

时间:2014-02-05 18:13:06

标签: c# sql procedure

我已经构建了一个过程,该过程应该在表中插入一个新行并返回其id。

CREATE PROCEDURE [InsertFood]
AS 
 DECLARE @ID TABLE (foodId INT)
 insert into TblFood
 OUTPUT INSERTED.foodId INTO @ID(foodId) 
 default values 
 select * from @ID
 return

当我运行此程序时,它总是返回0.

1 个答案:

答案 0 :(得分:1)

请参阅此MSDN帖子提供示例:Retrieving Identity or Autonumber Values

示例:

CREATE PROCEDURE dbo.InsertCategory
  @CategoryName nvarchar(15),
  @Identity int OUT
AS
INSERT INTO Categories (CategoryName) VALUES(@CategoryName)
SET @Identity = SCOPE_IDENTITY()

CREATE PROCEDURE [InsertFood]
AS 
 DECLARE @ID int 
 --insert data in table Example 
  ----INSERT INTO Production.Location (Name, CostRate, Availability, ModifiedDate)
  ----VALUES ('Damaged Goods', 5, 2.5, GETDATE()); 
 --insert data in table 
 select @ID =  SCOPE_IDENTITY()
 return @ID

您可以使用Scope_Identity()获取最后一个值。