DB Date insert works sometimes - sql-server-2008

I have the following line:
command.Parameters.Add("#date", SqlDbType.DateTime, 8).Value = date_of_trip;
where date_of_trip is a string containing 25-9-2013 (i.e. day-month-year)
This gives me an error message:
System.ArgumentException: Cannot convert 25-9-2013 to System.DateTime.
Parameter name: type ---> System.FormatException: String was not
recognized as a valid DateTime.
However, if date_of_trip is 1-1-2013, it seems to work perfectly!

You should parse the string to datetime before you send it to the db.
For example:
DateTime dt;
if(DateTime.TryParse(date_of_trip, out dt))
{
command.Parameters.Add("#date", SqlDbType.DateTime, 8).Value = dt;
// ...
}
else
{
// you should use a CompareValidator to check if it's a valid date
}
If you want to ensure that your given format will work even if the current-culture of the server will change you can use DateTime.TryParseExact with format "dd-MM-yyyy":
if (DateTime.TryParseExact(date_of_trip, "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out dt))
{
// ...
}

I guess it's because the server expects the first parameter to be a month. Try to use a real DateTime or the format yyyy-mm-dd (i.e. 2013-09-25), which should always work.

Related

How replace null value with {} in mysql?

I am trying to fetch value from table where null status value should get replace with {}(empty json object), so that I have used below mysql function
IFNULL(status, '{}') as status from table;
but its output is '{}' but I want output as only {} (without single quotes)
Also I have tried with below options as well
IFNULL(status, "{}") --> output -"{}"
IFNULL(status, '{}') --> output -'{}'
IFNULL(status, {}) --> output -Mysql error`
Expected output is only empty j son object Please suggest any solution.
Check the function JSON_UNQUOTE :
SELECT JSON_UNQUOTE(IFNULL(status, "{}")) as status FROM table
mysql is not supporting JSON_UNQUOTE function in case you are converting that mysql result into json object. so work around is to use replace string function(java or any other language) in your framework.
EX.
String rs = str.replace(""{","{"); // Replace '"{' with '{'
String rs = str.replace("}"","}"); // Replace '}"' with '}'

Convert String to Datetime (USING SSIS)

I want to insert a value "5/27/2013 16:42:37.490000" (Read from a flat file (DT_STR)) into a column(datetime) of SQL Server table . If I try to cast it with (DT_DBDATE) or DT_DBTIMESTAMP in a derived column , it gives an error .
[Derived Column [130]] Error: SSIS Error Code DTS_E_INDUCEDTRANSFORMFAILUREONERROR. The "component "Derived Column" (130)" failed because error code 0xC0049064 occurred, and the error row disposition on "output column "Derived Column 1" (155)" specifies failure on error. An error occurred on the specified object of the specified component. There may be error messages posted before this with more information about the failure.
How can I go about it ?
Thanks
The value is a datetime2 type .AFAIK SSIS doesn't support datetime2 .You need to store it in database as string and then update the column by converting it to datetime2.
Here is Microsoft Connect Issue
Update: Using DT_DBTIMESTAMP2 you can convert the string to proper datetime format
The below code works perfectly fine in Derived Column
(DT_DBTIMESTAMP2,7)"2013-5-27 16:42:37.490000"
7 is the precession here .The above code won't work if the format of datetime is different.For example MM/DD/YYYY HH:mm:ss.ffffff .
However you can use Script component and pass array of different datetime formats to Datetime.ParseExact function
Step1: Drag a Script component and create a new output column of DT_DBTIMESTAMP datatype and name it as NewDate.
Step2: Write the below C# code
public override void Input0_ProcessInputRow(Input0Buffer Row)
{
string[] format = new string[] { #"M/dd/yyyy HH:mm:ss.ffffff",
#"MM/dd/yyyy HH:mm:ss",
#"M/d/yyyy HH:mm:ss" ,
#"M/dd/yyyy HH:mm:ss.ffffff",
#"MM/dd/yyyy HH:mm:ss.ffffff",
#"M/d/yyyy HH:mm:ss.ffffff"};
DateTime dt = DateTime.ParseExact(Row.Date,
format ,
CultureInfo.InvariantCulture,
DateTimeStyles.None);
Row.newDate = dt;
}
I won't say it's the perfect solution, but just a workaround.
Format the input and then insert. The formatted data after using the below expression works well with either datetime or datetime2.
SUBSTRING(TMS_CREAT,(FINDSTRING(TMS_CREAT,"/",2) + 1),4) + "-" + SUBSTRING(TMS_CREAT,1,(FINDSTRING(TMS_CREAT,"/",1) - 1)) + "-" + SUBSTRING(TMS_CREAT,(FINDSTRING(TMS_CREAT,"/",1) + 1),2) + SUBSTRING(TMS_CREAT,(FINDSTRING(TMS_CREAT,"/",2) + 5),16)

Converting strings to DateTime in an IIF expression

I am using SSRS 2008R2 to create reports. The datasource is xml response from webservice. I want to return empty string if there is no data, but if there is row with data I want to convert it to another datetime format.
I am using IIF construction like this:
=IIF
(
LEN(Fields!DateOfReg.Value) <= 0,
"",
FORMAT(CDATE(DateTime.ParseExact(Fields!DateOfReg.Value,"M/d/yyyy hh:mm:ss tt",
System.Globalization.CultureInfo.InvariantCulture)), "dd.MM.yyyy HH:mm:ss")
)
When there is no data it shows #Error in the textbox and in the output:
String was not recognized as a valid DateTime
Does it mean that the IIF construction calculates both TRUE and FALSE statements? If so how can I make it short-circuit and don't convert row if there is no data?
Try the following:
=IIF
(
Fields!DateOfReg.Value= "",
"",
Datevalue(Cstr(Fields!DateOfReg.Value))
)
Yes, you are correct - IIF calculate both statements. But you can convert your empty string to "Nothing" using IIF and then try format it, something like this:
Format(IIF(Fields!DateOfReg.Value = "", Nothing, Fields!DateOfReg.Value), "yyyy/MM/dd")
Format function cause exception if you pass empty string but return empty string if you pass "Nothing".

Dapper And System.Data.OleDb DbType.Date throwing 'OleDbException : Data type mismatch in criteria expression'

Not sure if I should raise an issue regarding this, so thought I would ask if anybody knew a simple workaround for this first. I am getting an error when I try to use Dapper with OleDbConnection when used in combination with MS Access 2003 (Jet.4.0) (not my choice of database!)
When running the test code below I get an exception 'OleDbException : Data type mismatch in criteria expression'
var count = 0;
using (var conn = new OleDbConnection(connString)) {
conn.Open();
var qry = conn.Query<TestTable>("select * from testtable where CreatedOn <= #CreatedOn;", new { CreatedOn = DateTime.Now });
count = qry.Count();
}
I believe from experience in the past with OleDb dates, is that when setting the DbType to Date, it then changes internally the value for OleDbType property to OleDbTimeStamp instead of OleDbType.Date. I understand this is not because of Dapper, but what 'could' be considered a strange way of linking internally in the OleDbParameter class
When dealing with this either using other ORMs, raw ADO or my own factory objects, I would clean up the command object just prior to running the command and change the OleDbType to Date.
This is not possible with Dapper as far as I can see as the command object appears to be internal. Unfortunately I have not had time to learn the dynamic generation stuff, so I could be missing something simple or I might suggest a fix and contribute rather than simply raise an issue.
Any thoughts?
Lee
It's an old thread but I had the same problem: Access doesn't like DateTime with milliseconds, so you have to add and extension method like this :
public static DateTime Floor(this DateTime date, TimeSpan span)
{
long ticks = date.Ticks / span.Ticks;
return new DateTime(ticks * span.Ticks, date.Kind);
}
And use it when passing parameters:
var qry = conn.Query<TestTable>("select * from testtable where CreatedOn <= #CreatedOn;", new { CreatedOn = DateTime.Now.Floor(TimeSpan.FromSeconds(1)) });
Unfortunately, with current Dapper version (1.42), we cannot add custom TypeHandler for base types (see #206).
If you can modify Dapper (use the cs file and not the DLL) merge this pull request and then you do not have to use Floor on each parameters :
public class DateTimeTypeHandler : SqlMapper.TypeHandler<DateTime>
{
public override DateTime Parse(object value)
{
if (value == null || value is DBNull)
{
return default(DateTime);
}
return (DateTime)value;
}
public override void SetValue(IDbDataParameter parameter, DateTime value)
{
parameter.DbType = DbType.DateTime;
parameter.Value = value.Floor(TimeSpan.FromSeconds(1));
}
}
SqlMapper.AddTypeHandler<DateTime>(new DateTimeTypeHandler());

DateFormatting Error

I was trying to convert this format of String to Date and was unsuccessfull
"23-DEC-2008" to a Date Object ,it looks like its not accepting "-" and i could see NULL in the date object after formatting .
Can somebody let me know if u have come across this problem .
Thanks ,
Sudeep
The "-" shouldn't be an issue. I've converted SQL timestamp strings to Date objects with no problem (the format of SQL date strings is YYYY-MM-DD). What is the format string you're using? Try using the format string "DD-MMM-YYYY" and see if that works.
Edit
Sorry, my solution only applies to the DateFormatter class from Flex, and not Actionscript. After looking at the documentation for the Actionscript Date class I saw the following:
The year month and day terms can be separated by a forward slash (/) or by spaces, but never by a dash (-). (1)
If you're stuck using straight Actionscript, it looks as if you'll have to write your own parse method that accepts the "-".
this sort of works ...
public function parse(source:String):Date {
var ret:Date = new Date(0, 0, 0, 0, 0, 0, 0);
var parts:Array = source.split("-");
ret.fullYear = Number(parts[2]);
ret.setDate(Number(parts[0]));
var month:int = "jan,feb,mar,apr,may,jun,jul,aug,sep,oct,now,dec".split(",").indexOf(String(parts[1]).toLowerCase());
if (month == -1) throw "could not parse month";
ret.setMonth(month);
return ret;
}
but really, i don't like it ... if 'DEC' were 'Dec' , then
Date.parse("23-Dec-2008".split("-").join(" "))
would work ... but still ... i think, you should get something more robust ...
greetz
back2dos