Issue with sql query (not picking up parameter) - c#

I have the following code in c# for sql insert:
using (DM dbManager = new DM())
{
dbManager.Command.CommandText = #"Insert into TransactionLog(TransactionNumber,Amount
,studentID) Values (#trnumber,#amount,#studentID) ; SELECT SCOPE_IDENTITY() ;";
dbManager.Command.Parameters.AddWithValue("#trnumber", txnref);
dbManager.Command.Parameters.AddWithValue("#amount", amount);
dbManager.Command.Parameters.AddWithValue("#studentID",
Membership.GetUser().ProviderUserKey.ToString());
id = Convert.ToInt32(dbManager.Command.ExecuteScalar());
}
But failing to understand why am i getting this error:
System.Data.SqlClient.SqlException: The parameterized query '(#trnumber
nvarchar(4000),#amount nvarchar(5),#studentID nvarcha' expects the
parameter '#trnumber', which was not supplied.
Because the parameter is clearly in the query i tried changing the name of parameter same issue.
Any suggestions?

if (String.IsNullOrEmpty(txnref))
{
command.Parameters.AddWithValue("#trnumber", DBNull.Value);
}
else
command.Parameters.AddWithValue("#trnumber", txnref);

Try to put DBNull.Value if value is empty it will work! Also check your column accepts NULL

Related

I have problem with the parameters in a query in dataset

I have a .NET program with a dataset to an access/a sql DB.
I wrote a query and used 2 parameters, but I got an error:
Error in WHERE clause near '#'.
Unable to parse query text.
My query is:
SELECT DocID, DocCustomerNumber,
DocSessionID, DocTitle, DocKlaser, DocBarcodes
FROM VTblASMCustomersDocsAndGroupCodes
WHERE DocCustomerNumber = #cusNum AND
DocSessionID = #asmNum
Microsoft Access doesn't use named parameters. It uses positional parameters. So the order of the parameters is important when you set the values of the parameters.
Change your query to this:
SELECT DocID, DocCustomerNumber,
DocSessionID, DocTitle, DocKlaser, DocBarcodes
FROM VTblASMCustomersDocsAndGroupCodes
WHERE DocCustomerNumber = ? AND
DocSessionID = ?
Then use this code to pass the parameters:
cmd.Parameters.AddWithValue("param1", param1); // param1 = value of DocCustomerNumber
cmd.Parameters.AddWithValue("param2", param2); // param2 = value of DocSessionID

Procedure or function expects parameter, which was not supplied but the parameter is supplied [duplicate]

I have a stored procedure that has a parameter called UserName and in my code behind I have a SqlCommand object that I add the parameters to with the Add method. But for some reason when the command object tries to run the ExecuteReader method, it throws an exception. I am totally at a loss and have no idea why it's not recognizing the parameter. Before the ExecuteReader method is run I have a break point set so I can confirm the command object does contain the parameters being set, which is true. I know the stored procedure does return the correct data when the parameters are not added to the command object, but are hard coded in the actual stored procedure. Below is the exception message that is given in the catch block. I will also paste my code and first part of stored procedure. I would greatly appreciate any help in this issue, seeing that I have tried many different approaches to no avail. Thanks in advance.
Exception Message
Procedure or function 'someStoredProcedure' expects parameter '#UserName', which was not supplied.
Code Behind
private DataTable GetLossMitData(string code, DateTime? start, DateTime? end)
{
DataTable results = new DataTable();
string connectionString = ConfigurationManager.ConnectionStrings["asdf"].ConnectionString;
string userName = String.Empty;
try
{
using (SPSite site = new SPSite(ConfigurationManager.AppSettings["someName"]))
{
using (SPWeb web = site.OpenWeb())
{
userName = web.CurrentUser.Email.ToString();
}
}
using (SqlConnection connection1 = new SqlConnection(connectionString))
{
connection1.Open();
using (SqlCommand command1 = new SqlCommand("someStoredProcedure", connection1))
{
command1.Parameters.Add(new SqlParameter("#UserName", userName));
command1.Parameters.Add(new SqlParameter("#ProductCode", code));
SqlDataReader dr = command1.ExecuteReader(CommandBehavior.CloseConnection);
results.Load(dr);
}
connection1.Close();
}
}
catch (Exception ex)
{
}
return results;
}
Stored Procedure
#UserName nvarchar(256),
#ProductCode nvarchar(256),
#StartDate nvarchar(256) = '1/1/1900',
#EndDate nvarchar(256) = '12/30/2012'
AS
BEGIN
SET NOCOUNT ON;
Declare #UserID int
Select #UserID = Users.UserID
from Users
where Users.Email = #UserName
Try making sure that the command type is set to stored procedure.
mycommand.CommandType = System.Data.CommandType.StoredProcedure;
You will get this exception if the value of your 'userName' variable is null
If null is valid, then pass 'DBNull.Value' to the db instead:
command1.Parameters.Add(new SqlParameter("#UserName", (userName ?? DBNull.Value));
Command1.CommandType = System.Data.CommandType.StoredProcedure
This will force the ExecuteReader to perform the exec instead of just trying it as a flat command.
By default, the CommandText property needs to contain a complete SQL command, not just the name of the stored procedure.
You can change this by to set the SqlCommand's CommandType property to StoredProcedure.
Alternatively, you could explicitly pass the parameters, by changing the CommandText to "someStoredProcedure #UserName, #ProductCode"; this is a complete SQL statement and will work with the default CommandType of Text.
EDIT: I just tried it, and the only way to get that error message without setting CommandType to StoredProcedure (which he did not do) is if CommandText is EXEC someStoredProcedure. Passing a null parameter gives a different error.

C# Getting Return Value from Stored Procedure Is Not Working

I am trying to run a stored procedure returning a single integer value and I can't figure out where its going wrong. From what I've read the following should work but is not and I can't see where I'm going wrong.
Here is my stored procedure:
ALTER PROCEDURE [dbo].[getDDNTempID]
AS
BEGIN
declare #tempID int
select top 1 #tempID = tempID from tblDDNHdr order by tempID asc
if #tempID is null
return 0
else
return #tempID
END
Here is the code where I try to get the return value:
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["test"].ConnectionString))
{
SqlCommand cmd = new SqlCommand("getDDNTempID", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection.Open();
Int32 tempID = (Int32)cmd.ExecuteScalar();
if (tempID == 0) { tempID = -1; }
return tempID;
}
When this procedure is called I get a NullReferenceException and the line giving the error is:
Int32 tempID = (Int32)cmd.ExecuteScalar();
I would appreciate any guidance you guys could give.
Thanks
The return function in SQL Server is specifically to return completion codes to the calling function. As such, the values available to be returned are limited. What you need to do instead is to SELECT #tempID and treat it as a result set.
ExecuteScalar returns the value of the first column of the first row of the results. Your stored procedure does not return a result set.
Add a parameter to the SqlCommand.Parameters collection and set the Direction to ReturnValue. It will receive the return value from the stored procedure.
Please note that the return value is intended only for returning a status. You should use an OUTPUT parameter to return #TempId.

Issue with SqlCommand Parameters

When I execute the following query in SSMS I get the expected result i.e. '1'
SELECT TSID
FROM tblTimesheets
WHERE TSUser = 'PJW' AND TSDate = '2012-01-18';
However, when the SqlCommand is produced by the code in my application the ExecuteScalar fails (it simply causes the method to exit with no error message).
public int GetID(string paramUser, DateTime paramDate)
{
string strSql = "SELECT TSID " +
"FROM tblTimesheets " +
"WHERE TSUser = #TSUser AND TSDate = #TSDate;";
string strConnection = BuildConnectionString();
SqlConnection linkToDB = new SqlConnection(strConnection);
linkToDB.Open();
SqlCommand sqlCom = new SqlCommand(strSql, linkToDB);
sqlCom.Parameters.Add("#TSUser", SqlDbType.Text);
sqlCom.Parameters.Add("#TSDate", SqlDbType.Date);
sqlCom.Parameters["#TSUser"].Value = paramUser;
sqlCom.Parameters["#TSDate"].Value = paramDate;
int intResult = (Int32)sqlCom.ExecuteScalar();
linkToDB.Close();
return intResult;
}
I've stepped through the code and can confirm the parameters are PJW and 2012-01-18 as required, but the ExecuteScalar returns any data, which I know should be there based on my comparable query in SSMS.
Please assist.
Instead of SqlDbType.Text try any of the following, depending on the type of the column:
SqlDbType.VarChar
SqlDbType.NVarChar
SqlDbType.NText
SqlDbType.NChar
SqlDbType.Char
When the parameter is of DB type date, it is a good practice to defensively strip the time part on setting the parameter, like this:
sqlCom.Parameters.Add("#TSDate", SqlDbType.Date);
sqlCom.Parameters["#TSDate"].Value = paramDate.Date;
Please let me know if this does not help, and I'll remove my answer.
You say the ExecuteScalar fails with no error message. Wrap your code in a try-catch block to make sure any exceptions that ExecuteScalar() might be throwing are caught.
Other than that try and do as others have suggested and view the SQL produced using SQL Profiler, then run that SQL in SSMS to compare results.
SELECT TSID
FROM tblTimesheets
WHERE TSUser = 'PJW' AND TSDate = '2012-01-18';
Here U r passing the exact date as parameter
Where as while passing the parameter in to the stored procedure you are passing
"DateTime paramDate"
A date time variable
May be you need to parse to exact date format as supported by the stored procedure
i.e you need to format the paramDate variable to 'YYYY-mm-DD'
I am not sure.. Try it.. and reply if it helps or not !

Parameterized MySql INSERT query not having right parameters value

I'm trying to do a basic insert statement using a parameterized query. My problem is whatever the syntax I'm using it seems like the query is being done with all parameters set to null instead of their appropriate values (unless I hard-code the value in the command text).
Here is the code :
m_Command.CommandText = "INSERT INTO " + s_TracesTabelName + " (DateTimeTraceCreated,
Span, CenterFrequency, Data, DateTimeTestStarted) VALUES (#traceTime, #Span,
#CenterFrequency, #Data, #testTime)";
//just trying another syntax
MySqlParameter param = m_Command.CreateParameter();
param.MySqlDbType = MySqlDbType.Datetime;
param.ParameterName = "#traceTime";
param.Value = trace.TimeCreated;
m_Command.Parameters.Add(param);
//m_Command.Parameters.Add("#traceTime",MySqlDbType.Datetime,8,"DateTimeTraceCreated");
//m_Command.Parameters["#traceTime"].Value = trace.TimeCreated;
m_Command.Parameters.Add("#Span", trace.Span);
m_Command.Parameters.Add("#CenterFrequency", trace.CenterFrequency);
m_Command.Parameters.Add("#Data", data);
m_Command.Parameters.Add("#testTime", testStarted);
try
{
m_Connection.Open();
m_Command.ExecuteNonQuery();
}
catch(Exception e)
{
Console.WriteLine("Error Connecting to Database\n");
//errorlog
}
finally
{
m_Connection.Close();
}
The three different syntaxes lead me to null parameters' value.
ps : I've seen many people using command.Parameters.AddWithValue() method, but I seem to just don't have it.
Kind regards,
Ben
Could be your version of mysql ADO provider?
C# MySqlParameter problem
Try with ? instead of #

Categories

Resources