I am trying to return scalar from a database like this:
DbConnection cn = GetConnection2();
cn.Open();
// stored procedure
DbCommand cmd = GetStoredProcCommand(cn, "GetReason");
DbParameter param;
param = CreateInParameter("Reason_Number", DbType.String);
param.Value = number;
cmd.Parameters.Add(param);
param = CreateOutParameter("Result", DbType.String);
param.Direction = ParameterDirection.Output;
cmd.Parameters.Add(param);
cmd.ExecuteScalar();
string reason;
reason = cmd.Parameters["@Result"].Value.ToString();
if (cn.State == ConnectionState.Open)
cn.Close();
return reason;
Here is my stored procedure:
-- =============================================
-- Create date: Today
-- Description: Input Reason # and Return Full Reason Name
-- =============================================
ALTER PROCEDURE [dbo].[GetReason]
@Reason_Number nvarchar(50),
@Result nvarchar(50) output
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
SELECT @Result = Field1
FROM dbo.Reasons
WHERE Field1 LIKE @Reason_Number + '%';
END
I am getting an error on the ExecuteScalar line:
System.InvalidOperationException occurred
Message=”String[1]: the Size property has an invalid size of 0.”
What am I doing wrong?
If you want to use
ExecuteScalar, your stored proc needs to return the single row, single column from aSELECT:and then your code needs to read that value:
and use it from there. Of course, in that case, you also do not need an OUTPUT parameter in your C# code….
Word of warning: that
SELECTin your stored proc could potentially return multiple rows. You might want to add aTOP 1to your select – just to be safe: