【问题标题】:Call stored procedure and return a message调用存储过程并返回消息
【发布时间】:2017-01-14 07:03:23
【问题描述】:

我有以下 SQL Server 存储过程(缺少声明的参数,但我对此没有问题):

DECLARE @TotalRegistros AS INT = 0
DECLARE @ShowMsg AS NVARCHAR(50)    

SELECT @TotalRegistros = COUNT(*) 
FROM Tbl_Productos 
WHERE IdProducto = @Producto

IF @TotalRegistros < 3
BEGIN
    INSERT INTO Tbl_Productos (IdProducto, UnidadMedida, Precio, Activo) 
    VALUES (@Producto, @Medida, @Precio, @Activo)

    SET @ShowMsg = 'All fine!'
END
ELSE
BEGIN
    SET @ShowMsg = 'Error, you already have 3 rows.!'
END

SELECT @ShowMsg

我用这个 C# 代码执行这个存储过程:

public string ExecuteSP(Producto prod)
{
    int res = 0;
    string resp = "";

    SqlCommand cmd = new SqlCommand("SPName", conn);

    try
    {
        Open();
        cmd.CommandType = CommandType.StoredProcedure;

        cmd.Parameters.AddWithValue("@Producto", prod.Id);
        cmd.Parameters.AddWithValue("@Medida", prod.Tipo);
        cmd.Parameters.AddWithValue("@Precio", prod.Precio);
        cmd.Parameters.AddWithValue("@Activo", prod.Active);

        //CodeUpdated
        SqlParameter returnMessage = new SqlParameter("@ShowMsg", SqlDbType.NVarChar);
        returnMessage.Direction = ParameterDirection.ReturnValue;

        cmd.Parameters.Add(returnMessage);

        res = cmd.ExecuteNonQuery();

        resp = returnMessage.Value.ToString();
    }
    finally
    {
        Close();
    }

    return resp;
}

我知道我需要添加类似OutputParameter 的内容并添加@ShowMsg,但我不知道具体该怎么做!主要问题是我使用此代码从 WebMethod 执行此代码:

[WebMethod]
public string ExecuteC#Code(int id, string medida, string precio, string activo)
{
    string respuesta = "Error";

    try
    {
        Producto prod = new Producto(id, medida, precio, activo);
        //Code updated
        string resp = conn.ExecuteSP(prod);

        if (resp == "All fine!")
            respuesta = "Operacion realizada existosamente";
        else
            respuesta = "Already 3 rows with same Id..."
    }
    catch (Exception ex)
    {
        respuesta = "A ocurrido un error: " + ex.Message;
    }

    return respuesta;
}

就像我说的,我知道在执行存储过程后我需要做什么来获取消息,但是我不知道如何将该消息发送到我的 Web 方法。我知道我需要更改我的方法的数据类型,因为我希望得到 string 而不是 int

【问题讨论】:

  • 您正在选择@ShowMsg,而不是将其作为参数返回。因此,您需要 ExecuteScalar 而不是 ExecuteNonQuery
  • 你需要定义输出参数——因为你没有包含你可能错误的参数,但你也应该停止使用 AddWithValue:blogs.msmvps.com/jcoehoorn/blog/2014/05/12/…
  • 你可能只需要out,但你应该从那里弄清楚。
  • 我更新了我的代码,但现在的问题是我总是收到这条消息 Already 3 rows with same Id...,而当我只显示 string resp = conn.ExecuteSP 时,我得到 0。

标签: c# asp.net sql-server stored-procedures


【解决方案1】:

解决了!这是我从代码中修改的:

存储过程:

Declare @ShowMsg as nvarchar(50) TO Declare @ShowMsg as int 

set @ShowMsg = a number (10, 20, whatever)

C#代码:

public string ExecuteSP(Producto prod) TO public int ExecuteSP(Producto prod)

SqlParameter returnMessage = new SqlParameter("@ShowMsg", SqlDbType.NVarChar);

SqlParameter returnMessage = new SqlParameter("@ShowMsg", SqlDbType.Int);

resp = returnMessage.Value.ToString(); to Convert.ToInt32(resp = returnMessage.Value);

网络方法:

string resp = conn.ExecuteSP(prod); TO int resp = conn.ExecuteSP(prod);

最后

if (resp == "All fine!")
        respuesta = "Operacion realizada existosamente";
    else
        respuesta = "Already 3 rows with same Id..."

if (resp == 10)
    respuesta = "Operacion realizada existosamente";
else if (resp == 5)
    respuesta = "Already 3 rows with same Id...";

【讨论】:

  • 可能是因为这不是一个好方法,以后的读者一定要警惕。如果您有来自存储过程的文本消息要显示,您可以在输出参数中返回它或在结果集中选择。您未能探索任何一个选项,而是将文本压缩到 int 中。
【解决方案2】:

您应该使用 SQL Server 标量函数:

CREATE FUNCTION [dbo].[GetUserNameByID](@UserID int)
RETURNS nvarchar(max)
AS
BEGIN
    DECLARE @UserName nvarchar(max);

    SET @UserName = (SELECT TOP (1) [Login] 
                     FROM [dbo].[Users] 
                     WHERE ID = @UserID)
    RETURN @UserName
END

【讨论】:

    猜你喜欢
    • 2017-07-21
    • 2016-01-21
    • 2014-10-15
    • 1970-01-01
    • 2020-05-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-14
    • 1970-01-01
    相关资源
    最近更新 更多