简体   繁体   English

使用C#从SQL Server存储过程获取单个响应

[英]Getting single response from SQL Server stored procedure with C#

I've been wrestling with this for several days and have extensively dug through StackOverflow and various other sites. 我已经为此奋斗了几天,并广泛研究了StackOverflow和其他各种站点。 I'm literally drawing a blank. 我实际上是在画一个空白。 I'm trying to get a single result back from my stored procedure. 我正在尝试从存储过程中获取单个结果。

Here's my stored procedure: 这是我的存储过程:

ALTER PROC [dbo].[myHelper_Simulate]
    @CCOID nvarchar(100), @RVal nvarchar OUTPUT
AS
    DECLARE @UserID int 
    DECLARE @GUID uniqueidentifier

    SELECT @UserID = UserID 
    FROM [User] 
    WHERE CCOID = @CCOID AND deleted = 0

    SELECT @GUID = newid()

    IF @UserID > 0
        BEGIN
            INSERT [Audit] ([GUID], Created, UserID, ActionType, Action, Level)
            VALUES (@GUID, getdate(), @UserID, 'Authentication', 'Test Authentication', 'Success')

            SELECT @RVal = 'http://www.ttfakedomain.com/Logon.aspx?id=' + CAST(@GUID AS nvarchar(50))
            RETURN  
        END
    ELSE
        SELECT @RVal = 'Couldn''t find a user record for the CCOID ' + @CCOID
        RETURN 
GO

Originally the procedure was written to print out the result. 最初编写该程序是为了打印出结果。 I've added the @RVal and the RETURN in an attempt to get the value to pass back to my C# code. 我已经添加了@RValRETURN ,以使该值传递回我的C#代码。

Here's my C# routine ( svrConn has already been connected to the database): 这是我的C#例程( svrConn已经连接到数据库):

 private void btnSimulate_MouseClick(object sender, MouseEventArgs e)
 {
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = svrConn;
        object result = new object();

        cmd.CommandType = CommandType.StoredProcedure;
        cmd.CommandText = "[" + tDatabase + "].[dbo].myHelper_Simulate";
        cmd.Parameters.Add(new SqlParameter("@CCOID", txtDUserCCOID.Text.Trim()));
        cmd.Parameters.Add(new SqlParameter("@RVal", ""));
        cmd.Parameters.Add(new SqlParameter("RETURN_VALUE", SqlDbType.NVarChar)).Direction = ParameterDirection.ReturnValue;

        try
        {
            result = cmd.ExecuteScalar();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }

        if (result != null)
        {
            tString = result.ToString();
            MessageBox.Show(tString);
        }
    }

The problem is that result is coming back null. 问题是result返回空值。 I'm not sure if it's due to the stored procedure or how I'm setting my parameters and calling ExecuteScalar . 我不确定这是由于存储过程还是由于我设置参数并调用ExecuteScalar

SP return values are integers and are meant for error code. SP返回值是整数,用于错误代码。 The correct way is to use OUTPUT parameter. 正确的方法是使用OUTPUT参数。 You are assigning it correctly in the SP, you don't need the return statements. 您在SP中正确分配了它,不需要return语句。

In your C# code check the value after execution. 在您的C#代码中,检查执行后的值。 Use ExecuteNonQuery as there is no result set from the SP. 使用ExecuteNonQuery因为SP没有结果集。

var rval = new SqlParameter("@RVal", SqlDbType.NVarChar);
rval.Direction = ParameterDirection.Output;
cmd.Parameters.Add(rval);
cmd.ExecuteNonQuery();
result = rval.Value;

Don't need the return parameters or output parameters. 不需要返回参数或输出参数。 ExecuteScalar returns the first column of the first row of your result set. ExecuteScalar返回结果集第一行的第一列。 So just select the text you want to return, like so... 因此,只需选择要返回的文本,就像这样...

IF @UserID > 0
        BEGIN
            INSERT [Audit] ([GUID], Created, UserID, ActionType, Action, Level)
            VALUES (@GUID, getdate(), @UserID, 'Authentication', 'Test Authentication', 'Success')

            SELECT  'http://www.ttfakedomain.com/Logon.aspx?id=' + CAST(@GUID AS nvarchar(50))
        END
    ELSE
        SELECT 'Couldn''t find a user record for the CCOID ' + @CCOID


RETURN 

try 尝试

private void btnSimulate_MouseClick(object sender, EventArgs e) {
  using (SqlConnection con = svrConn) {
    using (SqlCommand cmd = new SqlCommand("myHelper_Simulate", con)) {
      cmd.CommandType = CommandType.StoredProcedure;

      cmd.Parameters.Add("@CCOID", SqlDbType.VarChar).Value = txtDUserCCOID.Text.Trim();
      var output = new SqlParameter("@RVal", SqlDbType.VarChar);
      output.Direction = ParameterDirection.Output;
      cmd.Parameters.Add(output);

      con.Open();
      cmd.ExecuteNonQuery();
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM