Inserting null value into DateTime field using DBValue.null - c#

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?

Related

How can we pass a empty Value to dateTime Parameter to a stored procedure from c#

How can we pass a empty Value to dateTime Parameter to a stored procedure
EndDate=null:
da.SelectCommand.Parameters.Add("#EndDate", SqlDbType.DateTime).Value = EndDate
As like the error message says it is not possible to convert the null or DbNull.Value to DateTime if you specify the expected datatype as SqlDbType.DateTime in add method. So better option is AddWithValue. Use like the following:
command.Parameters.AddWithValue("#dateparameter", DBNull.Value);
For more link
Try Below Code
da.SelectCommand.Parameters.Add("#StartDate", SqlDbType.NVarChar).Value
= StartDate.ToString("dd-MMM-yyyy");

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.

Raw SQL insert statement with optional parameter [duplicate]

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));

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 converting data type varchar to bigint (C# ASP.NET)

I'm trying to store a Int64 variable to data column with bigint data type. Following is my sql insert query and parameter declarations.
cmd.CommandText = "INSERT INTO tbl_subscribers VALUES ('#callerID2', '#timeStamp', '#unregisterDate ', '1')";
cmd.Parameters.Add("#callerID2", SqlDbType.BigInt);
cmd.Parameters["#callerID2"].Value = SMSObject.callerID;
cmd.Parameters.Add("#timeStamp", SqlDbType.DateTime);
cmd.Parameters["#timeStamp"].Value = SMSObject.timeStamp.ToString("yyyy-MM-dd HH:mm:ss");
cmd.Parameters.Add("#unregisterDate", DBNull.Value);
cmd.Parameters["#unregisterDate"].Value = DBNull.Value;
When it try to store the data, I get
Error converting data type varchar to bigint.
Any advices?
Change
INSERT INTO tbl_subscribers VALUES ('#callerID2', ...
to
INSERT INTO tbl_subscribers VALUES (#callerID2, ...
In case of parametrized sql query, you don't need to put single quote (') with parameter name.
cmd.CommandText = "INSERT INTO tbl_subscribers
VALUES (#callerID2, #timeStamp, #unregisterDate, '1')";

Categories

Resources