在c#中检索SQL Server输出变量

Mah*_*ine 6 c# asp.net stored-procedures sql-server-2008

我有一个存储过程:

ALTER PROCEDURE [dbo].[pr_Tbl_Test_Insert]
    @guidid uniqueidentifier output,
    @sname nvarchar(50)
AS
-- INSERT a new row in the table.
INSERT [dbo].[Tbl_Test]
(
    [id],
    [name]
)
VALUES
(
    ISNULl(@guidid, (newid())),
    @sname
)
Run Code Online (Sandbox Code Playgroud)

我需要id在C#中将它output放在c#中:

cmd.Parameters.AddWithValue("@guidid",_id);//_id is SqlGuid

cmd.Parameters.AddWithValue("@sname", "mehdi");

cmd.ExecuteNonQuery();
MessageBox.Show(_id.ToString());
Run Code Online (Sandbox Code Playgroud)

但是消息框显示空值!

我怎样才能归还身份证?

我改成了:

ALTER PROCEDURE [dbo].[pr_Tbl_Test_Insert] 
  @guidid uniqueidentifier output, 
  @sname nvarchar(50) 
AS 

DECLARE @NewID UNIQUEIDENTIFIER 
SET @NewID = newid(); 

-- INSERT a new row in the table. 
INSERT [dbo].[Tbl_Test]([id], [name]) VALUES(@NewID, @sname); 

SET @guidid = @NewID 
Run Code Online (Sandbox Code Playgroud)

和C#

SqlParameter outparam = cmd.Parameters.Add("@guidid",SqlDbType.UniqueIdentifier);
outparam.Direction = ParameterDirection.Output;

cmd.Parameters.AddWithValue("@sname", "mehdi");

cmd.ExecuteNonQuery();
MessageBox.Show(_id.Value.ToString());
Run Code Online (Sandbox Code Playgroud)

但它不会返回任何东西

mar*_*c_s 14

首先 - 如果它是OUTPUT参数,则不能.AddWithValue在C#中使用- 您需要使用:

SqlParameter outParam = cmd.Parameters.Add("@guidid", SqlDbType.Uniqueidentifier);
outParam.Direction = ParameterDirection.Output;
Run Code Online (Sandbox Code Playgroud)

而且,在您的T-SQL代码中,您需要将新值分配给输出参数!

ALTER PROCEDURE [dbo].[pr_Tbl_Test_Insert]
  @guidid uniqueidentifier output,
  @sname nvarchar(50)
AS

DECLARE @NewID UNIQUEIDENTIFIER
SET @NewID = newid();

-- INSERT a new row in the table.
INSERT [dbo].[Tbl_Test]([id], [name]) VALUES(@NewID, @sname);

SET @guidid = @NewID
Run Code Online (Sandbox Code Playgroud)

更新:如果您在SQL Server Mgmt Studio中运行它 - 它是否显示任何内容?

DECLARE @insertedID UNIQUEIDENTIFIER

EXEC dbo.pr_Tbl_Test_Insert @guidid = @insertedID OUTPUT,
                            @sname = N'TestUser' -- nvarchar(50)

SELECT @insertedID
Run Code Online (Sandbox Code Playgroud)

在你的C#中 - 你必须在调用后读出输出参数的值ExecuteNonQuery!

SqlParameter outparam = cmd.Parameters.Add("@guidid",SqlDbType.UniqueIdentifier);
outparam.Direction = ParameterDirection.Output;

cmd.Parameters.AddWithValue("@sname", "mehdi");

cmd.ExecuteNonQuery();

Guid newlyInsertedID = new Guid(cmd.Parameters["@guidid"].Value);
MessageBox.Show(newlyInsertedID.ToString());
Run Code Online (Sandbox Code Playgroud)


Dus*_*ges 5

在执行查询之前,需要指定参数的方向,在本例中为输出。例如:

cmd.Parameters.AddWithValue("@guidid",_id);//_id is SqlGuid

cmd.Parameters.AddWithValue("@sname", "mehdi");

cmd.Parameters["@guidid"].Direction = ParameterDirection.Output

cmd.ExecuteNonQuery();
MessageBox.Show(cmd.Parameters["@guidid"].Value.ToString());
Run Code Online (Sandbox Code Playgroud)

  • 这听起来具有感染力。小心!;-P (3认同)