I am trying to pull one piece of data from my database using a Stored Procedure that looks like this.
USE [PSD]
GO
/****** Object: StoredProcedure [dbo].[ocso_GetNextDTEventNumber] Script Date: 1/19/2017 10:12:19 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[ocso_GetNextDTEventNumber]
@EventNumber varchar(15) OUTPUT
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
--increment last number by 1
UPDATE LU_EVENT_NUMBERS SET evn_last_number = evn_last_number + 1 where evn_year = Year(GetDate())
--return event number to caller
--Get the next event number for all incidents
SELECT @EventNumber = evn_comp_formatted_next_num from LU_EVENT_NUMBERS where evn_year = Year(GetDate())
END
I test this procedure using this SQL Code
DECLARE @NewEventNumber varchar(15)
Execute dbo.ocso_GetNextDTEventNumber
@EventNumber = @NewEventNumber OUTPUT;
Print convert(varchar(15),@NewEventNumber)
And I get the results I would expect. Now when I try to get the results in my C# code which looks like this:
public string GetEventNumber(string enumber)
{
string results;
SqlConnection _con = new SqlConnection();
_con.ConnectionString =
"Data Source=ops-devsql;" +
"Initial Catalog=PSD;" +
"User id=****;" +
"Password=****;";
_con.Open();
{
using (SqlCommand _cmd = new SqlCommand("ocso_GetNextDTEventNumber", _con))
{
_cmd.Parameters.Add("@NewEventNumber", SqlDbType.VarChar, 15)
.Direction = ParameterDirection.Output;
_cmd.ExecuteNonQuery();
results = _cmd.Parameters["@NewEventNumber"].Value.ToString();
//results = (string)_cmd.Parameters["@NewEventNumber"].Value.ToString();
return results;
}
}
}
I get an empty string back. Why is this not working?
答案 0 :(得分:4)
您忘记告诉命令您要执行存储过程:
using (SqlCommand _cmd = new SqlCommand("ocso_GetNextDTEventNumber", _con))
{
_cmd.CommandType = CommandType.StoredProcedure;
//...
}
如果不指定它,则采用Text
的默认值(因此是一个简单的SQL查询)。我猜你有一个空的Try....Catch
,因为这会引起异常。
您还应该使用相同的参数名称:
_cmd.Parameters.Add("@EventNumber", SqlDbType.VarChar, 15).Direction = ParameterDirection.Output;
_cmd.ExecuteNonQuery();
results = _cmd.Parameters["@EventNumber"].Value.ToString();