我有点问题。我的价值总是null
。我不知道为什么。
以下代码:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[UsunTowar]
@id int output
AS SET NOCOUNT ON
BEGIN
if Exists (select top 1 Towar from Zamowienia where Towar = @id)
begin
set @id = 0
end
else
begin
delete from Towary where ID = @id
set @id = 1
end
END
现在c#:
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = "EXECUTE UsunTowar @id";
cmd.Parameters.Add("@id", SqlDbType.Int).Value = id;
cmd.Parameters["@id"].Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
string result = cmd.Parameters["@id"].Value.ToString();
con.Close();
值字符串'result'
始终为null
。我尝试了很多方法。返回值必须为0
或1
。
代码sql很好。请帮帮我。
答案 0 :(得分:1)
我用这个:
using(SqlConnection conn = new SqlConnection("myConnectionString"))
{
using(SqlCommand cmd = new SqlCommand("myStoredProcedure", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@id", SqlDbType.Int).Direction = ParameterDirection.Output;
try
{
conn.Open();
cmd.ExecuteNonQuery();
// -1 if null
int id = 0;
if (!int.TryParse(cmd.Parameters["@id"].value, out id))
id = -1;
}
catch
{
throw;
}
}
}