Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
190 views
in Technique[技术] by (71.8m points)

c# - Get value output from SQL Server stored procedure into variable

This seems to be a simple question but nevertheless I haven't found an answer yet.

I have the following stored procedure

CREATE PROCEDURE [dbo].[AllocateId]
AS
  BEGIN TRANSACTION

  UPDATE TOP(1) IdReservation 
  SET IsAllocated = 1
  OUTPUT DELETED.Id
  WHERE IsAllocated = 0 

  COMMIT TRANSACTION
  GO

It's been used in C# + EF code without a problem via ExecuteFunction of ObjectContext

ObjectResult<int> objectResult = ExecuteFunction<int>("AllocateId");

However when I try to call it directly from SQL script it doesn't seem to work

declare @Id int
EXEC @Id = [dbo].[AllocateId]

@Id is always 0. How do I get the value into @Id variable in sql script?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Procedure return value is different from result set(s) returned by that procedure. Your stored procedure returns a result set and does not return a return value (which ends up being null, which gets converted to 0 implicitly upon exiting the procedure).
To get the resultset your existing procedure retuns, you need insert ... exec:

declare @t table (id int);

insert into @t
exec [dbo].[AllocateId];

If you want to return a value as a return value as well, you should amend you stored procedure:

CREATE PROCEDURE [dbo].[AllocateId]
AS
BEGIN TRANSACTION

declare @id int;

UPDATE TOP(1) IdReservation
    SET @id = Id, IsAllocated = 1
    OUTPUT DELETED.Id
    WHERE IsAllocated = 0 

COMMIT TRANSACTION

return @id;

Then it will work in the way you describe in the question.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...