Conversion Errror when trying to insert DateTimeOffset into SQL table - sql

I am trying to insert a datetimeoffset value in SQL2014 using fluentmigrator but the query itself also fails in query manager. Any idea on how I should insert this?
Field - CreatedDate - DateTimeOffset(7)
Sending the value as a datetime works fine e.g. 2018/02/28 12:19:25
Adding the T marker or datetimeoffset causes the error
"Conversion failed when converting date and/or time from character string"
So both of these attempts fail
28/02/2018 12:42:37 +00:00
28/02/2018T12:42:37 +00:00
Here is a cut down version of the fluent code that fails
Insert.IntoTable("Tenant")
.Row(new
{
TenantID = Tenant1GUID,
TenantName = "MyName",
CreatedDate = DateTimeOffset.Now,
});
Here is a cut down version of the fluent code that works
Insert.IntoTable("Tenant")
.Row(new
{
TenantName = "MyName",
CreatedDate = DateTime.Now,
});
SQL Code that fails
INSERT INTO [dbo].[Tenant] ([TenantName], [CreatedDate])
VALUES ('Demo', '2018/02/28T12:19:25 +05:00:00')
SQL Code that works
INSERT INTO [dbo].[Tenant] ([TenantName], [CreatedDate])
VALUES ('Demo', '2018/02/28 12:19:25')

Iam not sure what exact error you getting but make sure the table column type should be set to datetimeoffset.

Related

Insert new timestamp value to acc table in kamailio

I want to add a new column to acc table. I created a new column in the acc table of type timestamp and named it ring_time. In every call I put the ring time to a $dlg_var like this:
$dlg_var(ringtime) = $Ts;
Then I add a extra column in config like this:
modparam("acc", "log_extra", "src_user=$fU;src_domain=$fd;src_ip=$si;" "dst_ouser=$tU;dst_user=$rU;dst_domain=$rd;ring_time=$dlg_var(ringtime)")
but when I try to test it, I always get:
db_mysql [km_dbase.c:122]: db_mysql_submit_query(): driver error on query: Incorrect datetime value: '1591361996' for column kamailio.acc.ring_time at row 1 (1292)
Jun 5 17:29:59 kamailio /usr/sbin/kamailio[22901]: ERROR: {2 102 INVITE 105a0f4a3d99a0a5558355e54b43f4e1#192.168.1.121:5060} <core> [db_query.c:244]: db_do_insert_cmd(): error while submitting query
Jun 5 17:29:59 kamailio /usr/sbin/kamailio[22901]: ERROR: {2 102 INVITE 105a0f4a3d99a0a5558355e54b43f4e1#192.168.1.121:5060} acc [acc.c:477]: acc_db_request(): failed to insert into database
Sounds like an error with the SQL INSERT query, if I had to guess I'd say you're being caught out by the date format in the SQL table not matching the date format you're pushing to it.
I don't know the structure of your database, but there's a simple trick I use for debugging SQL queries when I can't see the query being run;
Start up Wireshark/TCPdump on the machine and packet capture for all SQL traffic (MySQL is port 3306) and replicate the error.
From the packet capture and you'll be able to see the Query Kamailio's database engine ran.
If the error "db_mysql [km_dbase.c:122]: db_mysql_submit_query(): driver error on query: Incorrect datetime value: '1591361996' for column kamailio.acc.ring_time at row 1 (1292)", the '1591361996' looks like it is an epoch for the $dlg_var(ringtime). The "Incorrect datetime value" part of the error looks like the database is trying to store the value in datetime data type so a data type mismatch. Double-check and you may need either change the ringtime to convert to datetime or change the database column to a type that will take epoch.

org.h2.jdbc.JdbcSQLException: Unknown data type: "DATEADD"; SQL statement

I'm using h2 to inject the db during run time and testing, everything was working fine until I started trying to make the date field current, not hard-coded.
I thought it was related to the jdbc version I've and updated spring jdbc library to be the latest, but that didn't solve the problem.
This is the code I'm using to inject the data both on run-time and testing :
This code runs during run-time, and it works perfectly before I tried to make the date current.
ResourceDatabasePopulator resourceDatabasePopulator = new ResourceDatabasePopulator();
resourceDatabasePopulator.addScript(new ClassPathResource("schema.sql"));
resourceDatabasePopulator.addScript(new ClassPathResource("data.sql"));
DatabasePopulatorUtils.execute(resourceDatabasePopulator, dataSource); // This is what the DataSourceInitializer does.
For testing purpose, I'm using this code, as I mentioned, it was working perfectly before I tried to make the date current.
DataSource dataSource = new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2)
.addScript("classpath:schema.sql")
.addScript("classpath:data.sql")
.build();
data.sql file
INSERT INTO TABLE_X (
dayxx,
xxx
) VALUES
(CONVERT(char(50), DATEADD('DAY', -1,CURRENT_DATE()),126),'xxx')
Exception
Caused by: org.h2.jdbc.JdbcSQLNonTransientException: Unknown data type: "DATEADD"; SQL statement:
INSERT INTO TABLE_X ( dayxx, xxx ) VALUES (CONVERT(char(50), DATEADD('DAY', -1,CURRENT_DATE()),126),'XXX') [50004-200]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:505)
at org.h2.message.DbException.getJdbcSQLException(DbException.java:429)
at org.h2.message.DbException.get(DbException.java:205)
at org.h2.message.DbException.get(DbException.java:181)
at org.h2.command.Parser.parseColumnWithType(Parser.java:5971)
at org.h2.command.Parser.readFunctionParameters(Parser.java:3793)
at org.h2.command.Parser.readFunction(Parser.java:3772)
at org.h2.command.Parser.readTerm(Parser.java:4305)
at org.h2.command.Parser.readFactor(Parser.java:3343)
at org.h2.command.Parser.readSum(Parser.java:3330)
at org.h2.command.Parser.readConcat(Parser.java:3305)
at org.h2.command.Parser.readCondition(Parser.java:3108)
at org.h2.command.Parser.readExpression(Parser.java:3059)
at org.h2.command.Parser.parseValuesForCommand(Parser.java:1877)
at org.h2.command.Parser.parseInsertGivenTable(Parser.java:1817)
at org.h2.command.Parser.parseInsert(Parser.java:1749)
at org.h2.command.Parser.parsePrepared(Parser.java:954)
at org.h2.command.Parser.parse(Parser.java:843)
at org.h2.command.Parser.parse(Parser.java:815)
at org.h2.command.Parser.prepareCommand(Parser.java:738)
at org.h2.engine.Session.prepareLocal(Session.java:657)
at org.h2.engine.Session.prepareCommand(Session.java:595)
at org.h2.jdbc.JdbcConnection.prepareCommand(JdbcConnection.java:1235)
at org.h2.jdbc.JdbcStatement.executeInternal(JdbcStatement.java:212)
at org.h2.jdbc.JdbcStatement.execute(JdbcStatement.java:201)
at org.springframework.jdbc.datasource.init.ScriptUtils.executeSqlScript(ScriptUtils.java:472)
... 53 more
As reported in the docs, Convert function looks like this:
CONVERT ( value , dataType )
Converts a value to another data type.
Example:
CONVERT(NAME, INT)
Since you're passing
CONVERT(char(50), DATEADD('DAY', -1,CURRENT_DATE()),126)
The error states that DATEADD isn't a valid data type, since it's the value, not the type, so try using the right syntax.

How to fix error "Conversion failed when converting datetime from character string" in SQL Query?

The error that I found at the log is the one below.
'Illuminate\Database\QueryException' with message 'SQLSTATE[22007]:
[Microsoft][ODBC Driver 11 for SQL Server][SQL Server]Conversion
failed when converting date and/or time from character string. (SQL:
SELECT COUNT(*) AS aggregate
FROM [mytable]
WHERE [mytable].[deleted_at] IS NULL
AND [created_at] BETWEEN '2015-09-30T00:00:00' AND '2015-09-30T23:59:59'
AND ((SELECT COUNT(*) FROM [mytable_translation]
WHERE [mytable_translation].[item_id] = [mytable].[id]) >= 1)
)'
in
wwwroot\myproject\vendor\laravel\framework\src\Illuminate\Database\Connection.php:625
On the database, the DataType is datetime and is not null
Based on marc_s's answer I tried to change the format that I'm sending to the database. So I tried without the T on and [created_at] between '2015-09-30 00:00:00' and '2015-09-30 23:59:59'.
In my local, I'm using mysql, and the code works just fine. If I test the query above on the SQL Server client, both (with and without the T) works too.
How can I fix this problem without create any changes on the database itself?
The PHP/Laravel code:
$items = $items->whereBetween($key, ["'".$value_aux."T00:00:00'", "'".$value_aux."T23:59:59'"]);
With #lad2025 help, I got it to work.
Based on the point of his comments on my question, I changed in the code part (Laravel/PHP in this case) the format that I was passing. (In reality, I "removed" the format it self, and just added fields to a variable before passing to the query. This way, I let the database decide the format that he wants)
Instead of
$itens = $itens->whereBetween($key, ["'".$value_aux."T00:00:00'", "'".$value_aux."T23:59:59'"]);
I changed the code to this:
$sta = $value_aux."T00:00:00";
$end = $value_aux."T23:59:59";
$itens = $itens->whereBetween($key, [$sta, $end]);

Save datetime in sql table

How I can insert with a query a date like this? 2015-06-02T11:18:25.000
I have tried this:
INSERT INTO TABLE (FIELD) VALUES (convert(datetime,'2015-06-02T11:18:25.000'))
But I have returned:
Conversion failed when converting date and/or time from character string.
I tried also:
CONVERT(DATETIME, '2015-06-02T11:18:25.000', 126)
but it is not working:
Msg 241, Level 16, State 1, Line 1
Conversion failed when converting date and/or time from character string.
The entire query is:
INSERT INTO BOLLE_TEST_POPPER (QIDDIADE,QNUMBOLLA,QSELEZIONALE,QDATA,QORA,QPRIMAPESATA,QSECONDAPESATA,QIMP1,QIMP2,QIDCAUSALE,QIDCLIENTE,QIDDESTINAZIONE,QIDVETTORE,QIDSUBVETTORE,QIDCAMION,QORATRASITO,QNUMBOLLAINGRESSO,QDATABOLLAINGRESSO,QCOMMITTENTIDELTRASPORTO,QANNOTAZIONI,QANNOTAZIONIINBOLLA,QIDARTICOLO,QQANTITA,QIDAUTISTA,QNUMTESSERA,QNUMGETTONE,VALORETAB1,VALORETAB2,VALORETAB3,VALORETAB4,VALORETAB5,VALORETAB6,VALORETAB7,VALORETAB8,VALORETAB9,VALORETAB10,VALORETESTO1,VALORETESTO2,VALORETESTO3,VALORETESTO4,VALORETESTO5,VALORETESTO6,VALORETESTO7,VALORETESTO8,VALORETESTO9,VALORETESTO10) VALUES ('4','5234','-',
convert(datetime,'2015-06-02'),convert(datetime,'2015-06-02T11:18:25.000',126),'30020','20230','null','null','4','1','391','50','50','50','500',convert(datetime,'2015-06-02T11:14:06+02:00',126),'-','false','-','-','19','9790.00','1','BK994P','-','-','null','null','null','null','null','null','null','null','null','-','-','-','-','-','-','-','-','-','-');
What is wrong?
Try this:
INSERT INTO TABLE (FIELD) VALUES CONVERT(DATETIME, '2015-06-02T11:18:25.000', 126)
126 relates to ISO8601, which is the format yyyy-mm-ddThh:mi:ss.mmm.
This is the same format as the string '2015-06-02T11:18:25.000'.
For more information, see here.
For dates with a datetimeoffset (for example '2015-06-02T11:14:06+02:00' - note the +02:00 at the end), you will have to do this:
CONVERT(DATETIME, CONVERT(DATETIMEOFFSET,'2015-06-02T11:14:06+02:00'), 127)
The fully fixed query should be:
INSERT INTO BOLLE_TEST_POPPER (QIDDIADE,QNUMBOLLA,QSELEZIONALE,QDATA,QORA,QPRIMAPESATA,QSECONDAPESATA,QIMP1,QIMP2,QIDCAUSALE,QIDCLIENTE,QIDDESTINAZIONE,QIDVETTORE,QIDSUBVETTORE,QIDCAMION,QORATRASITO,QNUMBOLLAINGRESSO,QDATABOLLAINGRESSO,QCOMMITTENTIDELTRASPORTO,QANNOTAZIONI,QANNOTAZIONIINBOLLA,QIDARTICOLO,QQANTITA,QIDAUTISTA,QNUMTESSERA,QNUMGETTONE,VALORETAB1,VALORETAB2,VALORETAB3,VALORETAB4,VALORETAB5,VALORETAB6,VALORETAB7,VALORETAB8,VALORETAB9,VALORETAB10,VALORETESTO1,VALORETESTO2,VALORETESTO3,VALORETESTO4,VALORETESTO5,VALORETESTO6,VALORETESTO7,VALORETESTO8,VALORETESTO9,VALORETESTO10) VALUES ('4','5234','-',
convert(datetime,'2015-06-02'),convert(datetime,'2015-06-02T11:18:25.000',126),'30020','20230','null','null','4','1','391','50','50','50','500',CONVERT(DATETIME, CONVERT(DATETIMEOFFSET,'2015-06-02T11:14:06+02:00'), 127),'-','false','-','-','19','9790.00','1','BK994P','-','-','null','null','null','null','null','null','null','null','null','-','-','-','-','-','-','-','-','-','-');
You need a format. In this case, 126:
INSERT INTO TABLE (FIELD)
VALUES (convert(datetime,'2015-06-02T11:18:25.000', 126))
The list is here.
For time zones, you need 127, so you need to fix your values clause:
('4','5234','-',
convert(datetime,'2015-06-02'),convert(datetime,'2015-06-02T11:18:25.000',127),'30020','20230','null','null','4','1','391','50','50','50','500',convert(datetime,'2015-06-02T11:14:06+02:00',127),'-','false','-','-','19','9790.00','1','BK994P','-','-','null','null','null','null','null','null','null','null','null','-','-','-','-','-','-','-','-','-','-');
just try this. it worked for me.
if(isset($_POST['buttonsave']))
{
$vfidperiodo = preg_replace('#[^A-Za-z0-9]#i','',$_POST['idperiodo']);
$vfperiodo = ms_escape_string($_POST['periodo']);
$vffechainicio = $_POST['fecha_inicio'];
$query_in="INSERT INTO iperiodos (idperiodo, periodo, fecha_inicio)
VALUES ('".$vfidperiodo."','".$vfperiodo."','".$vffechainicio."')";
$sql_in = sqlsrv_query($conn,$query_in);
if ($sql_in) // Se eejectuto la sentencia SQL?
{
echo "SQLSuccess"; // Mensaje Afirmativo.
} else {
die( print_r( sqlsrv_errors(), true)); // Causa del error.
}
exit();
}
here's the DB and the Form images.

sql datetime overflow

net and I'm trying to insert a row into an entity, and I keep getting the following error:
SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
Here's my code on C# side:
public static void DumpToLog(string s, string userID)
{
var ler = new LoggedExceptionRepository();
var lex = new LoggedException();
lex.loginID = userID;
lex.dateTime = DateTime.Now;
lex.text = s;
ler.Add(lex);
ler.Save();
}
I've tried running sql server profiler and the only thing it executes is teh following (which if I execute directly against the sql server, it works!!):
exec sp_executesql N'insert [dbo].[LoggedExceptions]([text], [loginID], [dateTime])
values (#0, #1, #2)
select [ID]
from [dbo].[LoggedExceptions]
where ##ROWCOUNT > 0 and [ID] = scope_identity()',N'#0 nvarchar(max) ,#1 varchar(50),#2 datetime',#0=N'payment failed, rv = 0',#1='riz',#2='2010-11-03 12:05:00:690'
any suggestions as to what I can do next?
does it work if you hardcode the date parameter value? there could be something else going on, or it could be a misleading message.
Is there another datetime column in LoggedExceptions that you're not setting? There are cases where a framework will use DateTime.MinValue to fill in unspecified columns. Try setting explicit values for all datetime columns in LoggedExceptions.
found the issue. I just didn't realize that I was creating new objects and assigning them to existing entities earlier in teh code. so when it was saving the datacontext, it was having a problem with those earlier entities.