Procedure or function expects parameter, which was not supplied - c#

I am calling a simple stored procedure written in SQL Server 2008 with parameter from c# but it display error
"Procedure or function 'AddYear' expects parameter '#mYear', which was not supplied."
What's wrong with this code, i tried several things but didn't successed.
SqlCommand AddEquip = new SqlCommand("AddYear", dbConn);
SqlDataReader rdrEquip;
SqlParameter mP = new SqlParameter("#mYear",SqlDbType.VarChar ) ;
mP.Value = "1990";
AddEquip.Parameters.Add(mP);
rdrEquip = AddEquip.ExecuteReader();
-- Parameter Name & type are the same i use in the Procedure.

Seems like you forgot to set the SqlCommand as stored-procedure:
SqlCommand AddEquip = new SqlCommand("AddYear", dbConn);
AddEquip.CommandType = CommandType.StoredProcedure;

You need to add the parameter to your SqlParameter e.g:
mP = new SqlParameter("#mYear", SqlDbType.VarChar, PARAMETER_HERE);

if your Storedprocedure is expecting a parament than you have to pass it sqlcommand object
SqlParameter[] param = new SqlParameter[0];
param[0] = new SqlParameter("#mYear", "1990");
rdrEquip = SqlHelper.ExecuteReader(Con, CommandType.StoredProcedure, "SPC_proc", param);
i am using sqlhelper class here.

Related

sending parameters to stored procedure error [duplicate]

I am fairly new to C# and I'm trying to set up call to a stored procedure in my database which takes one parameter.
I get the error "Procedure or function 'SP_getName' expects parameter '#username', which was not supplied. "
My Stored procedure works ok when I supply it with the parameter and I run it via SQL management studio.
GO
DECLARE #return_value int
EXEC #return_value = [dbo].[SP_getName]
#username = 'bob101'
SELECT 'Return Value' = #return_value
GO
However when I try and call it the error is with how I'm passing the parameter in, but I can't spot what the issue is.
//create a sql command object to hold the results of the query
SqlCommand cmd = new SqlCommand();
//and a reader to process the results
SqlDataReader reader;
//Instantiate return string
string returnValue = null;
//execute the stored procedure to return the results
cmd.CommandText = "SP_getName";
//set up the parameters for the stored procedure
cmd.Parameters.Add("#username", SqlDbType.NVarChar).Value = "bob101";
cmd.CommandType = CommandType.Text;
cmd.Connection = this.Connection;
// then call the reader to process the results
reader = cmd.ExecuteReader();
Any help in spotting my error would be greatly appreciated!
I've also tried looking at these two posts, but I haven't had any luck:
Stored procedure or function expects parameter which is not supplied
Procedure or function expects parameter, which was not supplied
Thanks!
You have stated:
cmd.CommandType = CommandType.Text;
Therefore you are simply executing:
SP_getName
Which works because it is the first statement in the batch, so you can call the procedure without EXECUTE, but you aren't actually including the parameter. Change it to
cmd.CommandType = CommandType.StoredProcedure;
Or you can change your CommandText to:
EXECUTE SP_getName #username;
As a side note you should Avoid using the prefix 'sp_' for your stored procedures
And a further side note would be to use using with IDisposable objects to ensure they are disposed of correctly:
using (var connection = new SqlConnection("ConnectionString"))
using (var cmd = new new SqlCommand("SP_getName", connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#username", SqlDbType.NVarChar).Value = "bob101";
connection.Open();
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
// Do something
}
}
}
I had this problem, but it wasn't about parameter name of Command Type.
My problem was that when C# calls SP, for each parameter that has no value passes 'default' keyword (i found it in SQL Profiler):
... #IsStop=0,#StopEndDate=default,#Satellite=0, ...
in my case my parameter Type was DateTime :
#StopEndDate datetime
. I Solved my problem by seting default value to this parameter in Stored Procedure :
#StopEndDate datetime=null
Try remove #:
cmd.Parameters.Add("username", SqlDbType.NVarChar).Value = "bob101";

How to call an Oracle Procedure from C#

From C# Code, I'm trying to call a PACKAGE.PROCEDURE() from Oracle. In this simple example I should get one value from the procedure call, but all I get is error:
wrong number or types of arguments in call to 'RETURN_NUM'
The procedure is declared as follows:
PROCEDURE return_num(xNum OUT NUMBER) AS
BEGIN
xNum:= 50;
dbms_output.put_line('hello world ' || xNum);
END;
C# code:
Oraclecon.Open();
OleDbCommand myCMD = new OleDbCommand("TEST.return_num", Oraclecon);
myCMD.CommandType = CommandType.StoredProcedure;
myCMD.Parameters.Add("xNum", OleDbType.Numeric);
OleDbDataReader myReader;
myReader = myCMD.ExecuteReader();
Can some one please point out what I'm doing wrong. Then in a real scenario I would like to call a procedure that returns a set of values from a custom Type, such as:
TYPE r_interface_data IS RECORD
(
object_id VARCHAR2(16),
obj_type VARCHAR2(32)
);
TYPE t_interfase_data IS TABLE OF r_interface_data;
How can I approach that. Thanks!
UPDATE: In my particular case I ended-up doing the following approach
using (OleDbCommand cmd = new OleDbCommand("PACKAGE.procedure_name"))
{
cmd.CommandType = CommandType.StoredProcedure;
SqlManager sqlManager = new SqlManager();
return sqlManager.GetDataSet(cmd);
}
I don't think you're that far off... try this:
OracleCommand cmd = new OracleCommand("return_num", Oraclecon);
cmd.Parameters.Add(new OracleParameter("xNum", OracleDbType.Decimal,
ParameterDirection.Output));
cmd.CommandType = CommandType.StoredProcedure;
cmd.ExecuteNonQuery();
OracleDecimal d = (OracleDecimal)cmd.Parameters[0].Value;
double result = d.ToDouble();
result now contains the out parameter from the procedure.
I think your problem is you were attempting to use a DbDataReader on a stored procedure. DbDataReader is for queries.
Also, I used ODP.net -- that may or may not have contributed to your issue, that you were using Ole.

Linq Stored procedures, send parameter via System.Data.CommandType.StoredProcedure

I have a stored procedure and I need to send some parameters, just now I have:
readonly efacEntities _db = new efacEntities();
This is my model instance
And into my function I have:
_db.Database.Connection.Open();
var command = _db.Database.Connection.CreateCommand();
command.CommandText = "dbo.MyStoredProceadure ";
command.CommandType = System.Data.CommandType.StoredProcedure;
command.Parameters["#step"].Value = "668987";
command.CommandType = System.Data.CommandType.StoredProcedure;
var test = (command.ExecuteScalar());
But I get an error.
Is necessary send the parameter step or the parameter is not executing the command.ExecuteScalar, how I can send parameters in this query type?
Try this to correctly add the parameter to the command object prior to executing it:
command.Parameters.Add("#step", SqlDbType.Int).Value = 668987;
if #step is an int, or:
command.Parameters.Add("#step", SqlDbType.VarChar, 50).Value = "668987";
if #step is VARCHAR(50)
EDIT:
The above statements work provided that the command object is of type SqlCommand, which is clearly not the case here!
For a DbCommand object we can add a new parameter like this:
command.Parameters.Add(new SqlParameter()
{ ParameterName = "#step",
SqlDbType = SqlDbType.Int,
SqlValue = "66897"
})

Parameter order is incorrect when calling Oracle stored procedures using Oracle.ManagedDataAccess.Client

I am using latest Oracle.ManagedDataAccess.Client 11.2 .dll for getting data from Oracle to .net application. Is it required to pass parameter in same order as expected by the stored procedure?
From application side we are add parameter order to command object cmd is
KK_C
KK_C2
KK_C1
Stored procedure like
KK_C
KK_C1
KK_C2
And this is generic code I am not able pass parameter same order what the stored procedure expected. Because different stored procedures expect different parameter order
My method:
Public Function GetDataTable(ByRef xmlParams As XmlNodeList) As DataTable
{
Dim param As OracleParameter
Dim params As List(Of OracleParameter) = New List(Of OracleParameter)()
For Each node As XmlNode In xmlParams
param = New OracleParameter()
param.ParameterName = Convert.ToString(node.SelectSingleNode("name").InnerText)
param.OracleDbType = CType("112", OracleDbType)
param.Value =Convert.ToString(node.SelectSingleNode("name").InnerText)
Next
Dim addparam As OracleParameter
Dim cmd As OracleCommand
Dim objdt As DataTable
OpenConnection()
cmd = New OracleCommand()
cmd.Connection = _oracleConn
cmd.CommandText = sql
cmd.CommandType = CommandType.StoredProcedure
If Not params Is Nothing Then
For Each param As OracleParameter In params
addparam = New OracleParameter()
With addparam
.Direction = param.Direction
.OracleDbType = param.OracleDbType
If Left(param.ParameterName, 2) <> "KK_" Then
.ParameterName = "KK_" & param.ParameterName
Else
.ParameterName = param.ParameterName
End If
.Size = param.Size
.Value = param.Value
End With
cmd.Parameters.Add(addparam)
Next
End If
addparam = New OracleParameter("OO_remcursor", OracleDbType.RefCursor)
addparam.Direction = ParameterDirection.Output
cmd.Parameters.Add(addparam)
'fill the datatable
objdt = New DataTable(tblname)
Using objda As New OracleDataAdapter(cmd)
objda.Fill(objdt)
End Using
Return objdt
}
Stored procedure:
PROCEDURE GetDATA(KK_C IN NUMBER,KK_C1 IN NUMBER, KK_C2 IN NUMBER OO_remCursor OUT o_Cursor)
AS
BEGIN
OPEN o_remCursor FOR
SELECT .... ORDER BY LOWER(brand_alias);
END GetDATA;
As suggested by "Praveen G", if you want to call a stored procedure with named parameters without taking care of the paramaters declaration order, simply set "BindByName" to true
cmd.BindByName = True
Unfortunately, this property is not true by default (maybe for performance reasons)...

expects parameter '#ID', which was not supplied?

I am sending ID as outparameter but its giving error
System.Data.SqlClient.SqlException: Procedure or function
'usp_ClientHistoryItem' expects parameter '#ID', which was not
supplied.
Code
using (SqlCommand cmd = new SqlCommand("dbo.usp_ClientHistoryItem", conn))
{
SqlParameter parameterID = new SqlParameter("#ID", oReservation.Id);
parameterID.Direction = ParameterDirection.Output;
cmd.Parameters.Add(parameterID);
cmd.Parameters.Add(new SqlParameter("#PhoneNo", oReservation.ClientPhone));
cmd.Parameters.Add(new SqlParameter("#UserId", oReservation.UserID));
cmd.Parameters.Add(new SqlParameter("#Description", oReservation.Description));
cmd.Parameters.Add(new SqlParameter("#TestId", oReservation.TestId));
cmd.Parameters.Add(new SqlParameter("#StartDate", oReservation.StartDate));
cmd.ExecuteNonQuery();
returnValue = Convert.ToInt32(cmd.Parameters["#ID"].Value);
return returnValue;
}
You seem to be calling a stored procedure - yet you've never defined your SqlCommand to be a stored procedure:
using (SqlCommand cmd = new SqlCommand("dbo.usp_ClientHistoryItem", conn))
{
cmd.CommandType = CommandType.StoredProcedure; // add this line to tell ADO.NET it's a stored procedure!!
If you forget that line, then ADO.NET will try to interpret your stuff as an ad-hoc SQL statement....
this one solve my problem
may be it may helpful
cmd.CommandType = CommandType.StoredProcedure;
Your ID parameter in the stored procedure must be set as OUTPUT parameter. You are just setting it in code not in stored procedure.
Hy guys.
You have to set the property CommandType for the Command to StoredProcedure if that's the case. Otherwise it woun't detect the parameters.
One other reason this error is thrown is when the variable names don't match in your stored procedure and code because the code fails to find the parameter to which the value must be passed. Make sure they match:
Stored procedure:
create procedure getEmployee
#ID
as
Begin
select *
from emp
where id = #ID
End
Code:
SqlParameter p = new SqlParameter("#ID", id);
cmd.Parameter.Add(p);
The parameter #ID must match in both code and stored procedure
If you use dapper, you can use this construction
int id = 1;
var parameters = new DynamicParameters();
parameters.Add("#id", id, DbType.Int32, ParameterDirection.Input);
string sqlQuery = "[dbo].[SomeStoredProcedure]";
using (IDbConnection db = new SqlConnection(ConnectionString))
{
var result = await db.QueryAsync<SpResult>(sqlQuery, parameters, commandType: CommandType.StoredProcedure);
}

Categories

Resources