Raw SQL insert statement with optional parameter [duplicate] - c#

This question already has answers here:
Assign null to a SqlParameter
(20 answers)
Closed 7 years ago.
I'm trying to execute this command but get an exception:
cmd.CommandText = #"insert into Foo (Column1, Column2)
values (#Parameter1, #Parameter2)";
cmd.Parameters.Add(new SqlParameter("#Parameter1", 'bar'));
cmd.Parameters.Add(new SqlParameter("#Parameter2", null));
The exception states that #Parameter2 is expected but was not supplied.
Actually I'm providing it with null value. So how can I insert this very null into nullable Column2?

If you want to provide a NULL to the underlying database, use DBNull.Value:
cmd.Parameters.Add("#Parameter2", SqlDbType.Int).Value = DBNull.Value;
Adapt to whatever datatype your parameter really is (I'm just guessing here, since you didn't tell us - and I prefer to always explicitly tell the parameter what datatype it is)

Use DBNull.Value to represent a null value to the database:
cmd.CommandText = #"insert into Foo (Column1, Column2)
values (#Parameter1, #Parameter2)";
cmd.Parameters.Add(new SqlParameter("#Parameter1", 'bar'));
cmd.Parameters.Add(new SqlParameter("#Parameter2", DBNull.Value));

Related

System.Data.OleDb.OleDbException: 'Syntax error in UPDATE statement. '

I am getting this error while trying to update but I am not able to find any issue in update statement.
str = "UPDATE BillTable SET Bill_No = #billno, Bill_Year = #billYear, Voucher_No= #voucher, Date= #date, Group_ID= #groupname, Vendor_Id= #vendorname, Amount= #amount WHERE ID= #billID";
cmd = new OleDbCommand(str, cn);
cmd.Parameters.Add(new OleDbParameter("#billID", Convert.ToString(inovidid)));
cmd.Parameters.Add(new OleDbParameter("#billYear", Convert.ToString(fylabel.Text)));
cmd.Parameters.Add(new OleDbParameter("#billno", Convert.ToString(billno.Text)));
cmd.Parameters.Add(new OleDbParameter("#voucher", Convert.ToString(voucher.Text)));
cmd.Parameters.Add(new OleDbParameter("#date", Convert.ToString(DateTimePicker1.Text)));
cmd.Parameters.Add(new OleDbParameter("#groupname", Convert.ToString(groupidDB)));
cmd.Parameters.Add(new OleDbParameter("#vendorname", Convert.ToString(vendoridDB)));
cmd.Parameters.Add(new OleDbParameter("#amount", Convert.ToString(amount.Text)));
Conversion to string as well as out of order parameters may eventually cause a "data type mismatch" error or simply failure to execute (OleDbCommand parameters order and priority) but syntax error is most likely caused by use of Date as a field name. Date is a reserved word (intrinsic function). It even causes error with Execute command in Access VBA. Either rename the field or enclose in [ ] to define as field name: [Date]=#date.

Inserting null value into DateTime field using DBValue.null

Next code is giving me an exception:
cmd.CommandText = #"insert Table ";
cmd.CommandText += #"(StartTime,
EndTime)
values(#StartTime,
#EndTime)
SELECT CAST(scope_identity() AS int)";
cmd.Parameters.AddWithValue ( "#StartTime", DBNull.Value );
cmd.Parameters.AddWithValue ( "#EndTime", DBNull.Value );
cmd.ExecuteScalar();
The exception I am getting is Must declare '#StartTime' variable and same thing for #EndTime. Isn't the DBNull.Value used for things like this, what am I doing wrong?
I think the reason is the fact you are using AddWithValue.
You see, AddWithValue have to infer the data type of the parameter from the value (and meta data, if exists). When you use DBNull.Value and an inline SQL (as apposed to a stored procedure), there is simply no way to infer the data type.
Change the AddWithValue to Add:
cmd.Parameters.Add("#StartTime", SqlDbType.DateTime).Value = DBNull.Value;
cmd.Parameters.Add("#EndTime", SqlDbType.DateTime).Value = DBNull.Value
For more information, read Can we stop using AddWithValue() already?

Unable to insert null values in nullable column via stored procedure in C#

I have a SQL table where column is set to null. Now I am passing the null value from code via stored procedure and it throws an error which is, Procedure or function 'MyStoredProcedure' expects parameter '#Parameter', which was not supplied.
Now Confusing part for me is, if I add null condition and than pass DBNull.Value, it works fine but if I pass direct parameter which could be null than it throws error. I am trying to understand why? Am I missing something here?
Note: Just for information, passing parameter could be null based on the requirement.
Code:
string connString = _dbContext.Database.Connection.ConnectionString;
using (SqlConnection connection = new SqlConnection(connString))
{
connection.Open();
SqlCommand cmd = new SqlCommand("MyStoredProcedure", connection);
cmd.CommandType = CommandType.StoredProcedure;
scheduledEndDateTime = !string.IsNullOrEmpty(bulkUpdateSchedule.EndDate) && !string.IsNullOrEmpty(bulkUpdateSchedule.EndTime)
? (DateTime?)
Convert.ToDateTime(bulkUpdateSchedule.EndDate + " " + bulkUpdateSchedule.EndTime)
: null;
//This Fails
cmd.Parameters.AddWithValue("#scheduledEndDateTime", scheduledEndDateTime);
//This Works
if (scheduledEndDateTime != null)
{
cmd.Parameters.AddWithValue("#scheduledEndDateTime", scheduledEndDateTime);
}
else
{
cmd.Parameters.AddWithValue("#scheduledEndDateTime", DBNull.Value);
}
cmd.ExecuteReader();
connection.Close();
}
Stored Procedure:
ALTER PROCEDURE [dbo].[InsertScheduledBulkUpdateRecords]
#scheduledEndDateTime DATETIME,
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO ScheduledBulkUpdate (ScheduledEndDateTime)
VALUES (#scheduledEndDateTime)
END
Table Structure screen shot:
You've pretty much answered your own question null and DBNull.Value are different things. Where DBNull.Value means something to the database provider than null doesn't.
From MSDN on DBNull:
Do not confuse the notion of null in an object-oriented programming
language with a DBNull object. In an object-oriented programming
language, null means the absence of a reference to an object. DBNull
represents an uninitialized variant or nonexistent database column.

Unable to store value NULL in SQL

I am trying to store values in database.
How can I assign value NULL in the database, if it a an int.
Query:
#id varchar(10)
UPDATE [Table] SET
[id] = #id -- id is an int in sql
C# code:
I pass the value:
//dATABASE CONNECTION
db.StoredProcedure = "UpdateProjectValues";
db.Paramater("ID",TB_ID.TEXT); //tb_id.text=""
If it has value then that int will be stored but if I do not have the value, then 0 is getting stored, but i want NULL to be stored.
One solution strictly inside the database is:
UPDATE [Table]
SET [id] = (case when #id <> '' then cast(#id as int) end);
This makes the conversion explicit. However, it is probably better to set up the C# code to pass in an integer value that can take on a NULL value.
I thought I'd provide a few alternatives:
1). Handle the value in your stored procedure. Gordon's CASE statement works but since you are using SQL Server you also have the NULLIF() function which you can use like this:
UPDATE TABLE
SET [id] = NULLIF(#ID, '');
2.) Handle this in the C# code using a ternary operator like:
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "UpdateProjectValues";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#ID", string.IsNullOrWhiteSpace(TB_ID.TEXT) ? DBNull.Value : (object)TB_ID.TEXT);
There are other ways also, but these are simple examples.

Error with parameters not existing?

I am trying to get an insert/return primary key SQL query to run.
The query ends up looking like this:
declare #userid as integer;
insert into users (username,emailaddress,passwordhash,salt) values
(#username,#email,#password,#salt);
set #userid=scope_identity();
insert into groups (name,userid) values ('somegroup',#userid);
select #userid;
This simply goes into the SqlCommand.CommandText field. So this is executed as a single query
I then add the parameters like this: (cmd is a SqlCommand object)
cmd.Parameters.Add(new SqlParameter("#email",user.EmailAddress));
cmd.Parameters.Add(new SqlParameter("#username",user.Username));
cmd.Parameters.Add(new SqlParameter("#salt",user.Salt));
cmd.Parameters.Add(new SqlParameter("#password", user.PasswordHash));
I then execute the query with ExecuteScalar(); It will throw an error at this point though saying the parameter #email doesn't exist.
How do I fix this problem?
I've figured it out. If you send give null as the value of a parameter, it won't actually be added. So the solution(for me anyway, for you, it may involve DBNull) was to convert nulls into empty strings as so:
cmd.Parameters.Add(new SqlParameter("#email",user.EmailAddress ?? ""));
cmd.Parameters.Add(new SqlParameter("#username",user.Username));
cmd.Parameters.Add(new SqlParameter("#salt",user.Salt ?? ""));
cmd.Parameters.Add(new SqlParameter("#password", user.PasswordHash ?? ""));
You must prefix all parameter names with an #, so this will work:
cmd.Parameters.Add(new SqlParameter("#email",user.EmailAddress));
using (TransactionScope scope = new TransactionScope())
{
//Your code should be here in this case, as you are not using SP.
//So this will help you in case of multiple users
)
Or
Commit/Rollback Transaction

Categories

Resources