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?
You have forgotten to tell the command that you want to execute a stored-procedure:
using (SqlCommand _cmd = new SqlCommand("ocso_GetNextDTEventNumber", _con))
{
_cmd.CommandType = CommandType.StoredProcedure;
//...
}
If you don't specify it the default is taken which is Text
(so a plain sql query). I guess you have somewhere an empty Try....Catch
because this should cause an exception.
You should also use the same parameter name:
_cmd.Parameters.Add("@EventNumber", SqlDbType.VarChar, 15).Direction = ParameterDirection.Output;
_cmd.ExecuteNonQuery();
results = _cmd.Parameters["@EventNumber"].Value.ToString();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.