【发布时间】: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