OpenSqlConnection();
SqlCommand cmd = new SqlCommand("ReturnCharacterInfo", Con);
cmd.Parameters.AddWithValue("#CharacterID", CharacterID);
SqlDataReader dr = cmd.ExecuteReader();
When I run code you can see above, it throws exception
Procedure or function 'ReturnCharacterInfo' expects parameter '#CharacterID', which was not supplied.
but as you can see at the code, I'm suppying #CharacterID parameter and it's not empty or null.
Stored procedure:
[ReturnCharacterInfo] #CharacterID int
as
select
CharacterName, characterSurname, CharacterIsMale, CharacterAge,
CharacterMood, CharacterHealth, CharacterInCity, CharacterInLocation,
Cities.CityName, Locales.LocaleTitle
from
Characters
INNER JOIN
Cities on Cities.CityID = Characters.CharacterInCity
INNER JOIN
Locales on Locales.LocaleID = Characters.CharacterInLocation
Where
CharacterID = #CharacterID
Any suggestions?
I would try to explicitly specifying the type of the parameter - especially important if the value is null:
SqlCommand cmd = new SqlCommand("ReturnCharacterInfo", Con);
// added as per CodeNaked's comment - thanks! You've nailed it right on the head!
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#CharacterID", SqlDbType.Int).Value = CharacterID;
Also: do you have a typo anywhere?? Triple-check all occurrences of CharacterID - do you happen to have CharachterID or something like that somewhere in your code??
As CodeNaked pointed out, you need to set the command type of the SqlCommand. The SqlCommand object needs to be told it's a stored procedure because of the way that stored procedures are executed.
OpenSqlConnection();
SqlCommand cmd = new SqlCommand("ReturnCharacterInfo", Con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#CharacterID", CharacterID);
SqlDataReader dr = cmd.ExecuteReader();
Related
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";
I am trying to update my ms access db with windows application and I am having a hard time. When I run it I don't get any errors but it does update like once or twice when I test it but then doesn't work again if I do it again a third time.
This is the code I use
Conn.Open();
Command.CommandType = CommandType.Text;
Command.CommandText ="UPDATE TABLE SET c_qty=#qty WHERE id = #ID";
Command.Parameters.AddWithValue("#qty", txtQty.Text);
Command.Parameters.AddWithValue("#ID", txtID.Text);
Command.ExecuteNonQuery();
Conn.Close();
I felt I was doing this right or on the right track of having it correct but seems to be more of a issue then I thought. Any help would be great
Quantity and Id are hopefully integers and you should pass them as such.
Also Table is a reserved word, if this really is the name of your table you should enclose it with square brackets.
You should also pass in the correct db types in your parameters and not use AddWithvalue which does not allow this.
Code
Conn.Open();
Command.CommandType = CommandType.Text;
Command.CommandText ="UPDATE [TABLE] SET c_qty= ? WHERE id = ?";
Command.Parameters.Add(new OleDbParameter("#qty", OleDbType.Int) {Value = int.Parse(txtQty.Text)});
Command.Parameters.Add(new OleDbParameter("#ID", OleDbType.Int) {Value = int.Parse(txtID.Text)});
var rowsUpdated = Command.ExecuteNonQuery();
// output rowsUpdated to the log, should be 1 if id is the PK
Conn.Close();
Finally use using blocks for your Disposables. If you were to get an Exception here then connection would remain open until Garbage collection runs which means you might have a problem with other connection attempts to this Access database.
Revised with using blocks
using (OleDbConnection Conn = new OleDbConnection("connectionStringHere"))
using (OleDbCommand Command = new OleDbCommand("UPDATE [TABLE] SET c_qty= ? WHERE id = ?", Conn))
{
Command.Parameters.Add(new OleDbParameter("#qty", OleDbType.Int) {Value = int.Parse(txtQty.Text)});
Command.Parameters.Add(new OleDbParameter("#ID", OleDbType.Int) {Value = int.Parse(txtID.Text)});
Conn.Open();
var rowsUpdated = Command.ExecuteNonQuery();
// output rowsUpdated to the log, should be 1 if id is the PK
}
Finally OleDbCommand does not support named parameters, see OleDbCommand.Parameters
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.
I am VERY new when it comes to stored procedures and .NET, so I apologize in advance. I have a stored procedure that I am trying to use and I keep getting this error..."wrong number or types of arguments in call to 'COPY_ACCOUNT'". I am not sure why. Below is my stored procedure code followed by my C#.NET code. Any help is GREATLY appreciated. PLEASE.
create or replace procedure abstract_names.copy_account(r_rows_copied out int,
ar_old_acct in abn_headings.acct_no%type,
ar_new_acct in abn_headings.acct_no%type)
is
cnt int := 0;
begin
r_rows_copied := 0;
for r in (select heading from abn_headings where acct_no = ar_old_acct) loop
copy_heading(cnt, ar_old_acct, r.heading, ar_new_acct);
r_rows_copied := r_rows_copied + cnt;
end loop;
dbms_output.put_line('called abstract_names.copy_account '||to_char(r_rows_copied));
return; end;
Then my C#.NET code...
using System.Data.OracleClient;
try
{
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Parameters.Add("r_rows_copied", OracleType.Int32).Direction = ParameterDirection.Output;
cmd.Parameters.Add("ar_from_acct", OracleType.VarChar).Value = accountNumberDropDownList.SelectedValue.ToString();
cmd.Parameters.Add("ar_to_acct", OracleType.VarChar).Value = copyAccountDDL.SelectedValue.ToString();
cmd = new OracleCommand("abstract_names.copy_account", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.ExecuteNonQuery();
conn.Close();
/*
abstract_names.copy_account(r_rows_copied out int,
ar_from_acct in abn_headings.acct_no%type,
ar_to_acct in abn_headings.acct_no%type)
*/
}
finally
{
if (conn != null)
conn.Close();
}
My connection string is correct because I use it else where in my code and it works. The commented section is the stored procedure i am trying to use obviously. Please help me!
Just looking at your code and not being familiar with this OracleCommand object, it looks like you're creating parameters and then creating a new object in the middle wiping out all your parameter additions. Create a new object from the connection and then add your parameters. Attempting a stab at better code below. Also I would use using statements for any conneciton,commnand objects to ensure they get closed and disposed.
Edit: Didn't look too deep, my fault. It looks like the parameter names weren't matching up in the stored procedure and the .net code. Also since you're returning a value, I would use the ExecuteScalar method, ExeuteNonQuery won't return any data.
cmd = new OracleCommand("abstract_names.copy_account", conn);
cmd.Parameters.Add("r_rows_copied", OracleType.Int32).Direction = ParameterDirection.Output;
cmd.Parameters.Add("ar_old_acct ", OracleType.VarChar).Value = accountNumberDropDownList.SelectedValue.ToString();
cmd.Parameters.Add("ar_new_acct", OracleType.VarChar).Value = copyAccountDDL.SelectedValue.ToString();
cmd.CommandType = CommandType.StoredProcedure;
object value = cmd.ExecuteScalar();
conn.Close();
You assign a new instance to your cmd variable, then you lose reference to what you had done.
Here:
cmd.Parameters.Add("ar_to_acct", OracleType.VarChar).Value = copyAccountDDL.SelectedValue.ToString();
cmd = new OracleCommand("abstract_names.copy_account", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.ExecuteNonQuery();
conn.Close();
This is the wrong line:
cmd = new OracleCommand("abstract_names.copy_account", conn);
Just by looking at your code, I think you should simply remove that line and it should be OK.
Why does this return null?
//seedDate is set to DateTime.Now; con is initialized and open. Not a problem with that
using (SqlCommand command = new SqlCommand("fn_last_business_date", con))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("#seed_date", seedDate);//#seed_date is the param name
object res = command.ExecuteScalar(); //res is always null
}
But when I call this directly in the DB as follows:
select dbo.fn_last_business_date('8/3/2011 3:01:21 PM')
returns '2011-08-03 15:01:21.000'
which is the result I expect to see when I call it from code
Why, why, why?
Why does everyone insist on the select syntax?..
using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("calendar.CropTime", c))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#RETURN_VALUE", SqlDbType.DateTime).Direction = ParameterDirection.ReturnValue;
cmd.Parameters.AddWithValue("#d", DateTime.Now);
cmd.ExecuteNonQuery();
textBox1.Text = cmd.Parameters["#RETURN_VALUE"].Value.ToString();
}
try:
using (SqlCommand command = new SqlCommand("select dbo.fn_last_business_date(#seed_date)", con))
{
command.CommandType = CommandType.Text;
command.Parameters.AddWithValue("#seed_date", seedDate);//#seed_date is the param name
object res = command.ExecuteScalar(); //res is always null
}
You are actually getting an error that isn't being caught. You don't call scalar udfs like you call stored procedures.
Either wrap the udf in a stored proc, or change syntax. I'm not actually sure what that is because it isn't common...
Ah ha: see these questions:
How to use SQL user defined functions in .NET?
Calling user defined functions in Entity Framework 4