I have a stored procedure like below. How I can print the message in the output parameter @ErrorMsg
in my aspx page.
ALTER PROC [dbo].[ItemMasterIns]
(
@ItemCode VARCHAR(30),
@ItemDesc VARCHAR(100),
@ErrorMsg VARCHAR(200) OUTPUT
)
AS
BEGIN
IF EXISTS ( SELECT 'X' FROM [DataBase].[dbo].[Table] WHERE Code= @Code )
BEGIN
SET @ErrorMsg = 'GIVEN CODE EXIST!'
RETURN 0
END
ELSE
BEGIN
INSERT INTO [DataBase].[dbo].[Table]([Code], [Descr])
VALUES (@Code, @Desc)
END
END
If you want to get the [@errormessage] and print it on ASPX page, then you need to use ParameterDirection.Output
Basing on your comment, I write a full code and tested it on my local, it works as expected. Please try again.
using System;
using System.Data;
using System.Data.SqlClient;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Program.RunSPWithParameterOutput();
}
public static void RunSPWithParameterOutput()
{
string PredefinedConnectionString = "Data Source=localhost;Initial Catalog=Adventure;Integrated Security=SSPI";
using (SqlConnection conn = new SqlConnection(PredefinedConnectionString))
using (SqlCommand cmd = new SqlCommand("dbo.usp_ItemMasterIns", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
// set up the parameters
cmd.Parameters.Add("@ItemsCode", SqlDbType.VarChar, 30);
cmd.Parameters.Add("@ItemsDesc", SqlDbType.VarChar, 30);
cmd.Parameters.Add("@ErrorMessage", SqlDbType.VarChar, 200).Direction = ParameterDirection.Output;
// set parameter values
cmd.Parameters["@ItemsCode"].Value = "test";
cmd.Parameters["@ItemsDesc"].Value = "test";
// open connection and execute stored procedure
conn.Open();
cmd.ExecuteNonQuery();
// read output value from @ErrorMessage
string ErrorMessage = cmd.Parameters["@ErrorMessage"].Value.ToString();
Console.WriteLine(ErrorMessage);
conn.Close();
}
}
}
}
Test store procedure deployed on my local.
create procedure usp_ItemMasterIns (@ItemsCode varchar(100),
@ItemsDesc varchar(30),
@ErrorMessage varchar(200) output
)
as
begin
set @ErrorMessage='test error message'
end