C#存储过程错误返回值

时间:2014-05-19 20:17:50

标签: c# stored-procedures

我从未使用过在C#中返回值的存储过程。我试着在互联网上寻找,但我找不到任何有用的东西。可能是因为我真的不明白它是如何运作的。

STORED PROCEDURE - dbo.sp_Admin_AddNewUser

USE [NGE]
GO
/****** Object:  StoredProcedure [dbo].[sp_Admin_AddNewUser]    Script Date: 05/19/2014 15:07:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[sp_Admin_AddNewUser]
(
    @firstname  varchar(50),
    @lastname   varchar(50),
    @middlename     varchar(50),
    @phone_office   varchar(50),
    @retval varchar(50) OUTPUT
)
 AS

INSERT INTO EDUSER
    (firstname,
    lastname,
    middlename,
    phone_office,
    synceratorInactiveFlag)
VALUES(
    rtrim(ltrim(@firstname)),
    rtrim(ltrim(@lastname)),
    rtrim(ltrim(@middlename)),
    rtrim(ltrim(@phone_office)),
    'A')

IF @@error = 0 
SELECT @retval = rtrim(ltrim(SCOPE_IDENTITY()))

--Add the user to the group
IF EXISTS (SELECT 1 FROM EDGROUP WHERE [group_id] = @GroupID)
BEGIN
    INSERT INTO [NGE].[dbo].[EDGROUPPRACTICE]
    ([group_id]
    ,[user_id])
    VALUES
     (@GroupID
     ,@retval)
END

调用商店程序的代码:

SqlCommand cmd = new SqlCommand("dbo.sp_Admin_AddNewUser", conn);
cmd.CommandType = CommandType.StoredProcedure;
conn.Open();

cmd.Parameters.Add(new SqlParameter("@firstname","Test"));
cmd.Parameters.Add(new SqlParameter("@lastname", "User"));
cmd.Parameters.Add(new SqlParameter("@middlename", "M"));
cmd.Parameters.Add(new SqlParameter("@phone_office", "(555) 555-5555"));

cmd.Parameters.Add("@retval", "");
cmd.Parameters["@retval"].Direction = ParameterDirection.ReturnValue;

cmd.ExecuteNonQuery();
tempUserID = (string)cmd.Parameters["@retval"].Value; //GET ERROR HERE

我收到错误:

  

过程或函数需要参数'@retval'未提供

2 个答案:

答案 0 :(得分:1)

尝试以这种方式添加参数:

SqlParameter firstName = cmd.Parameters.Add("@firstname", SqlDbType.VarChar, 50);
nikParam.Direction = ParameterDirection.Input;
//Rest of the params
//Then the output param
SqlParameter retValOutput = cmd.Parameters.Add("@retval", SqlDbType.VarChar, 50);
nikParam.Direction = ParameterDirection.Output;

我希望这会有所帮助;)

答案 1 :(得分:0)

它不是返回值,它只是输出参数。使用

cmd.Parameters["@retval"].Direction = ParameterDirection.Output;

而不是

cmd.Parameters["@retval"].Direction = ParameterDirection.ReturnValue;

要获得返回值,您必须

RETURN @retval 
在你的SP中