Why if I have this stored procedure created with an output parameter, I'm getting the following error:
sp_DTS_InsertLSRBatch expects parameter #ErrorMsg which was not
supplied
Stored procedure code:
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
ALTER PROCEDURE [dbo].[sp_DTS_InsertLSRBatch]
#LSRNbr varchar(10),
#BatchNbr varchar(10),
#ErrorMsg varchar(20) output
AS
BEGIN
SET NOCOUNT ON;
if not exists(select *
from tblDTS_LSRBatch (nolock)
where LSRNbr=#LSRNbr and BatchNbr=#BatchNbr)
begin
-- check if BatchNbr exists under another LSR
-- if not add (LSR, BatchNbr) else error
if not exists(select *
from tblDTS_LSRBatch (nolock)
where BatchNbr=#BatchNbr)
insert into tblDTS_LSRBatch (LSRNbr,BatchNbr) values (#LSRNbr, #BatchNbr)
else
set #ErrorMsg = 'Batch dif LSR'
end
END
C# code:
SqlConnection conn = new SqlConnection(ConnStr);
try
{
conn.Open();
for (int i = 0; i <= lbxBatch.Items.Count - 1; i++)
{
SqlCommand cmd = new SqlCommand("sp_DTS_InsertLSRBatch", conn);
cmd.Parameters.Add(new SqlParameter("#LSRNbr", txtLSR.Text));
cmd.Parameters.Add(new SqlParameter("#BatchNbr", lbxBatch.Items[i].ToString()));
//Output parameter "ErrorMsg"
SqlParameter pErrorMsg = new SqlParameter("#ErrorMsg", SqlDbType.VarChar, 20);
pErrorMsg.Direction = ParameterDirection.Output;
cmd.CommandType = CommandType.StoredProcedure;
cmd.ExecuteNonQuery(); <--- ERROR
In your code you haven't added the pErrorMsg parameter. Add this line:
cmd.Parameters.Add(pErrorMsg);
Moreover, in your Stored Procedure, you must set #ErrorMsg sql output variable to an appropriate value like an empty string or double double-quotes ("") in the if condition parts of your SP code,as a good coding practice.
You're creating the pErrorMsg parameter, but where are you adding it to your command?
Related
I am executing a SQL Server stored procedure in C#, but both my output parameters are returned blank. But when I run this stored procedure directly in SSMS, then I get values for both parameters. I used same input order no.
Can anyone tell me what's wrong in my code? Thank you
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("wt_find_open_pick_ticket_count", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#input_order_no", order_no);
cmd.Parameters.Add("#status", SqlDbType.Int).Direction = ParameterDirection.Output;
cmd.Parameters.Add("#results", SqlDbType.VarChar, 1000).Direction = ParameterDirection.Output;
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show(cmd.Parameters["#status"].Value.ToString());
MessageBox.Show(cmd.Parameters["#results"].Value.ToString());
}
ALTER procedure wt_find_open_pick_ticket_count
#input_order_no varchar(20),
#results varchar(1000) OUTPUT,
#status int OUTPUT
AS
SELECT
status =
CASE
WHEN COUNT(oe_pick_ticket.pick_ticket_no)>0 THEN 0
ELSE 1
END,
results =
CASE
WHEN COUNT(oe_pick_ticket.pick_ticket_no)> 0 THEN 'Message'
ELSE ''
END
FROM oe_pick_ticket with (nolock)
WHERE
oe_pick_ticket.order_no = #input_order_no
AND oe_pick_ticket.invoice_no IS NULL
AND oe_pick_ticket.delete_flag = 'N'
AND oe_pick_ticket.print_date > '2014-01-01'
GROUP BY oe_pick_ticket.order_no
This stored procedure returns a resultset. It does not return output parameters. In order to return output paramters, SP has to change to something like:
select
#paramout1 = val1,
#paramout2 = val2
Notice "#" that is preceding parameter names.
I have a stored procedure called lastID like this:
CREATE PROCEDURE lastID(#id varchar(64) OUTPUT)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #f VARCHAR(64);
SELECT TOP 1 #f = work_id
FROM workorder
WHERE (RIGHT(work_id,2)) = (RIGHT(Year(getDate()),2))
ORDER BY work_id DESC;
IF(#f IS NULL)
BEGIN
SET #f = 'No work orders';
SET #id = #f;
RETURN #id;
END
ELSE
BEGIN
SET #id = #f;
RETURN #id;
END
END
This stored procedure returns the last id from the table workorder, now I'm trying to execute this procedure in C#, this is the code:
private void lastWorkId()
{
String strConnString = "Server=.\\SQLEXPRESS;Database=recalls;Integrated Security=true";
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "lastID";
cmd.Parameters.Add("#id", SqlDbType.VarChar, 64).Direction = ParameterDirection.Output;
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
String id = cmd.Parameters["#id"].Value.ToString();
lastid.Text = id.ToString(); //Putting the return value into a label
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
}
}
I don't know what are wrong with my code, because an exception is displayed, and this says
Conversion failed when converting the varchar value ' OT- 003-16 ' to data type int
I was wrong about my first answer, here is the updated answer:
Your stored procedure is setup with an OUTPUT parameter of type VARCHAR(64).
Within your proc you have a couple of RETURN #id; statements, which is actually returning a VARCHAR(64). You only need to set your OUTPUT variable within the stored procedure. The RETURN statement expects an integer expression. Here's the updated fixed sproc using OUTPUT appropriately:
ALTER PROCEDURE [dbo].[lastID](#id varchar(64) OUTPUT)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #f VARCHAR(64);
SELECT TOP 1 #f = work_id FROM workorder WHERE (RIGHT(work_id,2)) = (RIGHT(Year(getDate()),2)) ORDER BY work_id DESC;
IF(#f IS NULL)
BEGIN
SET #f = 'No work orders';
SET #id = #f;
END
ELSE
BEGIN
SET #id = #f;
END
END
Error is basically should get fixed by cast
((RIGHT(work_id,2)) as int)
But code can be further condensed and improved.
CREATE PROCEDURE lastID(#id varchar(64) OUTPUT)
AS
BEGIN
SET NOCOUNT ON;
SELECT TOP 1 #id = isnull(work_id , 'No work orders') FROM workorder WHERE cast ((RIGHT(work_id,2)) as int)= (RIGHT(Year(getDate()),2)) ORDER BY work_id DESC;
RETURN #id;
END
Still i get an error "The formal parameter "#result" was not declared as an OUTPUT parameter, but the actual parameter passed in requested output".
here is my code in c#
SqlCommand cmd = new SqlCommand("AddRoomType", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#TypeName", TxtType.Text);
cmd.Parameters.Add("#result", SqlDbType.Int);
cmd.Parameters["#result"].Direction = ParameterDirection.Output;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
my stored procedure in SQL server
Create proce AddRoomType
#TypeName nvarchar(50),
#result int
as
if(exists(select * from TblRoomTypes where RoomType = #TypeName))
set #result = 0
else
begin
set #result = 1
insert into TblRoomTypes (RoomType) values (#TypeName)
end
please Help
Set Your Parameter as OUTPUT when creating the Stored Procedure
create proc AddRoomType
#TypeName nvarchar(50),
#result int out -- ** NOTE it's declared as 'OUT' **
as
if(exists(select * from TblRoomTypes where RoomType = #TypeName))
set #result = 0
else
begin
set #result = 1
insert into TblRoomTypes (RoomType) values (#TypeName)
end
This is my stored procedure code
ALTER procedure [Proc_Add_User]
(#UserId varchar(20),
#UserName varchar(100),
#Page_Name varchar(20),
#AccessIndicator int,
#CreatedBy varchar(50),
#returnStatus varchar(50) output)
as
DECLARE #intErrorCode INT
DECLARE #Page_Indicator INT
begin
BEGIN TRAN
Set #Page_Indicator = (select Page_Indicator from Pages where Page_Name=#Page_Name);
if (select count(*) from Users where UserId=#UserId and UserName=#UserName) > 0 begin
if (select count(*) from User_Credentials where Page_Indicator=#Page_Indicator and
UserId=#UserId ) > 0
set #returnStatus='User already has access'
else
insert into User_Credentials(UserId,Page_Indicator,Access_Indicator,CreatedBy)
values (#UserId,#Page_Indicator,#AccessIndicator,#CreatedBy)
SELECT #intErrorCode = ##ERROR
IF (#intErrorCode <> 0) GOTO PROBLEM
end
else begin
insert into Users(UserId,UserName,CreatedBy)
values(#UserId,#UserName,#CreatedBy)
SELECT #intErrorCode = ##ERROR
IF (#intErrorCode <> 0) GOTO PROBLEM
insert into User_Credentials(UserId,Page_Indicator,Access_Indicator,CreatedBy)
values (#UserId,#Page_Indicator,#AccessIndicator,#CreatedBy)
SELECT #intErrorCode = ##ERROR
IF (#intErrorCode <> 0) GOTO PROBLEM
end
COMMIT TRAN
if(#returnStatus is null)
set #returnStatus='Success';
PROBLEM:
IF (#intErrorCode <> 0) BEGIN
set #returnStatus= 'Unexpected error occurred!'
ROLLBACK TRAN
end
end
And I am calling this from the code pasted below:
Con.Open();
cmd = new OleDbCommand();
cmd.Connection = Con;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "Proc_Add_User";
cmd.Parameters.Clear();
cmd.Parameters.Add("#UserId", SqlDbType.VarChar).Value = userLanId;
cmd.Parameters.Add("#UserName", SqlDbType.VarChar).Value = userName;
cmd.Parameters.Add("#Page_Name", SqlDbType.VarChar).Value = pageName;
cmd.Parameters.Add("#AccessIndicator", SqlDbType.Int).Value = accessIndicator;
cmd.Parameters.Add("#CreatedBy", SqlDbType.VarChar).Value = createdBy;
OleDbParameter output = new OleDbParameter("#returnStatus", SqlDbType.VarChar);
output.Direction = ParameterDirection.Output;
cmd.Parameters.Add(output);
int result = cmd.ExecuteNonQuery();
I am getting the error mentioned at the ExecuteNonQuery statement. What's confusing to me is I am able to execute the stored procedure in SSMS but not from my application (front-end). I provided the same values too yet it fails from my app.
I double checked to make sure the order of parameters passed match and are of same data type but still it throws this error. I can paste my stored proc code here if wanted so let me know..Thanks in advance!
EDIT
OOPS! I just realized that all the inserts are all happening and getting committed fine in the database. It's just this error is getting caught inside catch block in my app. Any ideas?
I can not ignore it because based on the return value of ExecuteNonQuery(), I have some statements and also it's not going through the code present after ExecuteNonQuery().
This is most likely because you are using SqlDbType with OleDbParameters:
OleDbParameter output = new OleDbParameter("#returnStatus", SqlDbType.VarChar);
This causes .NET to use the OleDbParameter(String, Object) constructor, setting the value of the parameter to SqlDbType.VarChar which it assumes is an int.
You should use this instead:
OleDbParameter output = new OleDbParameter("#returnStatus", OleDbType.VarChar);
And change your calls to cmd.Parameters.Add to use OleDbType as well.
Alternatively, you could use System.Data.SqlClient instead of OleDb
What is the true sequence to make this code run as I tried many time but I don't get a valid result
// the code of SQL stored procedure
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
ALTER PROC [dbo].[login_proc] #username Varchar =50, #password varchar=50
as
Declare #user_name varchar , #pass_word varchar, #result varchar
Set #user_name = #username
Set #pass_word = #password
if EXISTS (select username , password from data where username= #user_name)
set #result= 1
else
set #result=0
return #result
and asp.net code is
SqlConnection conn = new SqlConnection ("Data Source=ANAGUIB-LAPNEW\\SQLEXPRESS;Initial Catalog=account;Integrated Security=True");
SqlCommand cmd = new SqlCommand("login_proc",conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter paramReturnValue = new SqlParameter();
paramReturnValue.ParameterName = "#result";
paramReturnValue.SqlDbType = SqlDbType.Int;
cmd.Parameters.Add(paramReturnValue);
cmd.Parameters["#result"].Direction = ParameterDirection.Output;
conn.Open();
cmd.Parameters.AddWithValue("#username", TextBox1.Text);
cmd.Parameters.AddWithValue("#password", TextBox2.Text);
cmd.ExecuteScalar();
string retunvalue = (string)cmd.Parameters["#result"].Value;
if (retunvalue == "1")
{
Response.Redirect("hello.aspx");
}
else
{
Response.Write("error");
}
conn.Close();
You're executing .ExecuteScalar() so you're expecting back a result set with a single row, single column from the stored procedure - but you're not selecting anything at the end of your stored proc!
You need to change your last line in the stored proc from
return #result
to
SELECT #result
and then it should work.
Add another parameter for the return value
ALTER PROC [dbo].[login_proc]
#username Varchar = 50,
#password Varchar = 50,
#result int OUTPUT
Examples can be viewd here.
Did you try this one;
Use the
return #result
and in c#
int resultID = Convert.ToInt32(cmd.ExecuteScalar());
Also remove next line
cmd.Parameters[""].value;
I'm unable to login any suggestions, both in case of stored procedure and codebehind can anyone provide solution to this,,,plz,,,