Save datetime in sql table - sql

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.

Related

SQL - Error converting data type varchar to numeric

I have data in a table that has decimals and stored as a varchar type data. I need to place that data into another table with column that is data type of decimal(18,5)
I get error:
Error converting data type varchar to numeric
The problem is with this Share column
Query I have is
SELECT IFS.Bin,CFL.CUSIP,IFS.[FROM],
--IFS.Shares
--SUM(isnull(cast(IFS.Shares as money),0))
--CAST(isnull(IFS.Shares,0) AS VARCHAR(30))
Shares =
Convert(
DECIMAL(18,5),
CASE
WHEN IFS.Shares LIKE '%[^0-9]%' THEN IFS.Shares --NULL
ELSE IFS.Shares
END)
FROM
mfclearing.ICE.ImportFileStaging IFS INNER JOIN
mfclearing.Production.ClearingFundList CFL ON
IFS.[From] = CFL.NasdaqSymbol
So if I try to only use IFS.Shares that doesn't work, I was trying some other SUM and CAST , but the last thing is that I'm trying to do is that Shares = Convert .....
Should not be too relevant to this, but I do want to do an insert into and so I do have an insert statement right above that Select statement
INSERT INTO [InterclassExchangeBatchDetails](Bin,FromCusip,FromSymbol,Shares)
The data that I'm working with for reference that is causing the problem, here is a sample of it
521.92100000000005
9906.8510000000006
542.529
1043.8409999999999
3129.0839999999998
5285.4120000000003
104.367
126.98
332.02499999999998
530.12300000000005
575.57799999999997
895.56899999999996
1052.9349999999999
1167.0619999999999
1180.9939999999999
1630.8030000000001
247.232
2136.2040000000002
667.95500000000004
947.78599999999994
148.36000000000001
223.994
238.42699999999999
255.25700000000001
257.56999999999999
259.70600000000002
317.90199999999999
317.90199999999999
317.90199999999999
360.59199999999998
366.84399999999999
374.35000000000002
376.90199999999999
393.11500000000001
397.37200000000001
399.47699999999998
449.72699999999998
463.60899999999998
474.68599999999998
488.11599999999999
491.245
504.67399999999998
509.97899999999998
530.47199999999998
535.93299999999999
537.69799999999998
549.40599999999995
552.41700000000003
581.32600000000002
608.05100000000004
Just use TRY_CONVERT():
Shares = TRY_CONVERT(DECIMAL(18,5), IFS.Shares)

Conversion Errror when trying to insert DateTimeOffset into SQL table

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.

Problems converting a char to datetime

I've written following code & im trying to search this table for rows between a specific period:
SELECT 'RWH' + P.Hospital_Number AS MRN,
P.Date_of_birth,
pd.Clinic_date AS Date_Seen,
pd.Clinic_type_No
FROM (Patient_diabetes AS pd
INNER JOIN Patients AS p ON pd.Patient_No = p.Patient_No)
INNER JOIN Staff AS s ON pd.Seen_by1_No = s.Staff_No
WHERE (((pd.Clinic_type_No)=241))
--AND hospital_number like '%63028%'
AND CONVERT(datetime,pd.Clinic_Date,121) BETWEEN '02/04/2015' AND '24/09/2015'
ORDER BY p.Date_of_birth,
pd.Clinic_date DESC
But I get the following error, any ideas how to fix this?:
Msg 242, Level 16, State 3, Line 2 The conversion of a char data type
to a datetime data type resulted in an out-of-range datetime value.
I suggest you to change:
AND CONVERT(datetime,pd.Clinic_Date,121) BETWEEN '02/04/2015' AND '24/09/2015'
To this:
AND CONVERT(date,pd.Clinic_Date,121) BETWEEN '2015-04-02' AND '2015-09-24'
I think the problem here in the BETWEEN '02/04/2015' AND '24/09/2015'
By default '24/09/2015' converts into "mm/dd/yyyy" format data. So there is no 24th month.
Try to explicitly point the format of string data:
BETWEEN CONVERT(datetime,'02/04/2015',103)
AND CONVERT(datetime,'24/09/2015',103)

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

Select Max number from column doesnt return max

I am running a sql query to return the largest value in a column back to the program.
The sql query i run is..
select MAX([Line No]) from table
I am using sql server 2008.
The table has 3 rows, 'Line No' has values 50, 90, 100
the max value i expect to be returned is 100,
but im getting 90..why?
EDIT:
string LineNo = "0";
//LineNo
string SQLlineno = "select MAX(CAST([Line No] As Int)) from Saved_Order_Import where [order no] = '"
+ ordernumber + "'";
SqlCommand myCommandlineno = new SqlCommand(SQLlineno, myConnection);
SqlDataReader readerline;
try
{
readerline = myCommandlineno.ExecuteReader();
if (readerline.HasRows)
{
while (readerline.Read())
{
try
{
if (readerline.GetString(0) != null)
{
LineNo = (readerline.GetString(0) + 10).ToString();
}
}
catch (Exception ex) { return "{\"error\":\"line : " + ex.ToString() + "\"}"; }
}
}
readerline.Close();
}
catch (Exception ex)
{
// return "{\"error\":\"Other One11" + ex.ToString() + "\"}";
}
Your column is likely not a numeric type but a string type (char, nchar, varchar, nvarchar). So, it is sorting alphabetically, and 9 comes after 1.
The easiest thing is to change to the correct data type for that column. If you can't do that, you'll need to cast back to the correct type inside the MAX.
E.g.,
select max(cast ([Line No] as int))
from table
If you have some values in that column that cannot be converted to a number that you want to filter out, you can do:
select max(cast ([Line No] as int))
from table
where isnumeric([Line No]) = 1
Or, to only show the non-numeric values, so you can fix them, you could do:
select *
from table
where isnumeric([Line No]) = 0
For more robust integer detection, see this article: Can I Convert This String to an Integer?
select MAX(cast([Line No] as int)) from table
UPADTE:
Call the ExecuteScalar on your SqlCommand not GetSring.
int max = (int)myCommandlineno.ExecuteScalar();
As RedFilter's answer,it may be a different type. Cast the column value to a numeric type and then apply the Max function
select MAX(CAST(LineNo AS INT) from table
To get the numeric maximium from text data, you have to cast the values:
select max(cast([Line No] as int)) from table
If you have other alphanumeric values in your column that cannot be converted to int, and you want to ignore them, but you still want to return a string to the code, you can do something like this:
select cast(max(cast(LineNo AS int) as varchar(10))
from table
where isnumeric([LineNo] = 1)
However, if the column is intended to hold integers, I recommend you schedule some development time to change the column type and migrate any non-integers to acceptable values. You can really get yourself into trouble if you don't use proper data types.