ServiceStack OrmLite and DateTimeOffset support in the UK - sql

I am getting an issue with OrmLite and DateTimeOffset support. I am based in the UK and believe that it is related.
I have a table with a column of type DateTimeOffset.
I get the following SQL error when trying to insert into the DateTimeOffset column:
Msg 241, Level 16, State 1, Line 1
Conversion failed when converting date and/or time from character string.
I have run SQL Profiler and can see that the SQL being executed is as follows:
INSERT INTO "Table"
("InsertedDateTime")
VALUES
('23/04/2013 09:30:48 +00:00')
I am pretty sure that this is an issue with the dd/mm/yy vs mm/dd/yy. If I convert the SQL to the following, it works fine:
INSERT INTO "Table"
("InsertedDateTime")
VALUES
('23-Apr-2013 09:30:48 +00:00')
Have I got something configured incorrectly or is there something I need to do to get this to work correctly?

You just need to change the default date format. Try this one -
SET DATEFORMAT dmy
DECLARE #temp TABLE (col DATETIMEOFFSET)
INSERT INTO #temp (col)
SELECT '23-Apr-2013 09:30:48 +00:00'
INSERT INTO #temp (col)
SELECT '2013-04-23 09:30:48 +00:00'
INSERT INTO #temp (col)
SELECT '2013/04/23 09:30:48 +00:00'
INSERT INTO #temp (col)
SELECT '23/04/2013 09:30:48 +00:00'

Related

UPDATE SET FORMAT not working in SQL Server 2016?

FORMAT instruction works in a SELECT but has no effect in an UPDATE:
SELECT ##VERSION
DROP TABLE IF EXISTS #t;
CREATE TABLE #t(DateMin datetime);
INSERT INTO #t VALUES ('2019-13-01 00:00:00')
SELECT * FROM #t
UPDATE #t SET DateMin = FORMAT(DateMin, 'dd/MM/yyyy');
SELECT * FROM #t;
SELECT #DateMin AS a, FORMAT(#DateMin, 'dd/MM/yyyy') AS b
A type like DATETIME isn't stored with a format.
So if one updates a DATETIME with a string in a certain format, it doesn't matter for the stored value in the DATETIME field.
The formatted string is implicitly converted to a datetime. At least if it's in a format that's valid.
The function FORMAT, which returns a NVARCHAR is rather used for representation of the datetime field in a query.
Or if one wants to INSERT/UPDATE a string field with a datetime in a certain format. But that should be avoided, because it's much easier to work with a datetime than a string.
If you want to change that format for the user use this:
set dateformat dmy;
By running this statement:
DBCC USEROPTIONS;
you will see your dateformat is ydm so you can alway back it up to that if this is not what you wanted :)
You cannot set the output format of a datetime in the datetime itselfs.
If you need to output the datetime as formatted char/varchar, you need to use the convert-function when you select the data:
SELECT CONVERT(char(10), CURRENT_TIMESTAMP, 101) -- format: MM/dd/yyyy
SELECT CONVERT(char(10), CURRENT_TIMESTAMP, 103) -- format: dd/MM/yyyy
In your case:
SELECT #DateMin AS a, CONVERT(char(10), #DateMin, 103) AS b
That works as expected.
If you want to have a mutable data-type, you need to declare it as sql_variant:
DROP TABLE IF EXISTS #t;
CREATE TABLE #t(DateMin sql_variant);
INSERT INTO #t VALUES ('2019-01-13T00:00:00')
UPDATE #t SET DateMin = FORMAT(CAST(DateMin AS datetime), 'dd''/''MM''/''yyyy');
SELECT * FROM #t;
Also, your format-expression needs to explicitly put the / into quotation marks, aka 'dd''/''MM''/''yyyy', otherwise sql-server replaces it with the date-separator specific to the current culture, which would be . in my case.
Just use convert with option 103 instead, it works on all versions of sql-server and it's probably faster.
Also, your insert-statement fails on some versions of sql-server, because iso-date-format is 2019-01-13T00:00:00 and not 2019-13-01 00:00:00
Correct is:
INSERT INTO #t VALUES ('2019-01-13T00:00:00')
Also
DROP TABLE IF EXISTS #t;
is sql-server 2016+ only, otherwise you need
IF OBJECT_ID('tempdb..#t') IS NOT NULL DROP TABLE #t
And post sql-server 2005, you should use datetime2 instead of datetime.
You shouldn't use datetime anymore, because datetime uses float, and as such is imprecise - if you insert an iso datetime value, it can do funny things because of the float-point-machine-epsilon, e.g. set it to the next day if you have 23:59:59.999, just as a scary example.
I advise you to never use the sql_variant type. If you have a temp-table with defined columns, just create another column where you will write the char/varchar value to.

Convert function SQL Server

I'm trying to convert the data of a column from varchar(255) to Timestamp.
I went to Microsoft documentation and it's not working
Code:
SELECT
["Data Nascimento"]
FROM
[leoninos] AS Original,
CONVERT(VARCHAR, ["Data Nascimento"]) AS VARCHAR,
CONVERT(timestamp(6, 4), ["Data Nascimento"]) AS timestamp;
Error:
Msg 156, Level 15, State 1, Line 53.
Incorrect syntax next to keyword 'CONVERT'.
What is the syntax error?
Thanks in advance.
Don't use varchar and timestamp as column aliases. Try this:
SELECT ["Data Nascimento"] as original
TRY_CONVERT(varchar(255), ["Data Nascimento"]) AS type_varchar
-- TRY_CONVERT(timestamp(6, 4), ["Data Nascimento"]) AS type_timestamp
FROM [leoninos] ;
Notes:
timestamp isn't really appropriate. I don't know what you are trying to do.
The FROM clause goes after the SELECT list.
Don't use SQL keywords as column names (even if they are not reserved).
Use try_convert() in case the conversion fails.
It's hard to tell what you are doing- but it appears that you are trying to select a table and also two scalars at once. Try just doing the CONVERT statements on their own with sample values:
SELECT CONVERT(int, '10'), CONVERT(date, '20180720')
Then, once you have it working for some sample values, you can convert column values:
CREATE TABLE #test (a NVARCHAR(max))
INSERT INTO #test VALUES ('january 1 2018')
INSERT INTO #test VALUES ('20180720')
SELECT a, CONVERT(date, a) FROM #test
DROP TABLE #test

Updating timestamp with custom format (dd/MM/yyyy HH:MM:ss.FFFFFFF)

How to write a statement that will update the date field in database with dd/MM/yyyy HH:MM:ss.FFFFFFF format.
I have select query which return the require string
SELECT FORMAT(CURRENT_TIMESTAMP, 'dd/MM/yyyy HH:MM:ss.FFFFFFF')
I tried with
update ORDER
set timedate=FORMAT(CURRENT_TIMESTAMP, 'dd/MM/yyyy HH:MM:ss.FFFFFFF')
WHERE ID='288'
But returning error :
SQL Error [8152] [22001]: String or binary data would be truncated.
com.microsoft.sqlserver.jdbc.SQLServerException: String or binary data would
be truncated.
My field datatype is varchar 27
CREATE TABLE AYAM.dbo.ORDER (
ID int NOT NULL IDENTITY(1,1),
TIMEDATE varchar(27) NOT NULL,
CONSTRAINT PK_ORDER_DATA PRIMARY KEY (ID,TIMEDATE)
) GO;
I am using MSSQL 2016
Why do you ask for FFFFFFF when CURRENT_TIMESTAMP function returns only 3 decimal numbers? Use SYSDATETIME() function to get better precision.
I was unable to re-produce the error. What SQL Server version do you use?
create table #test (timedate varchar(27))
insert into #test VALUES ('test');
update #test
set timedate=FORMAT(SYSDATETIME(), 'dd/MM/yyyy HH:MM:ss.FFFFFFF')
select * from #test
drop table #test
The output is: 18/09/2017 12:09:44.6914345
UPDATED:
the same test was done using your table structure. No errors ...
INSERT INTO dbo.[ORDER] (TIMEDATE) VALUES ('test')
GO 300
update [ORDER]
set timedate=FORMAT(CURRENT_TIMESTAMP, 'dd/MM/yyyy HH:MM:ss.FFFFFFF')
WHERE ID='288'

How to insert date values into table

How can I insert into table with different input using / ,with date datatype?
insert into run(id,name,dob)values(&id,'&name',[what should I write here?]);
I'm using oracle 10g.
Since dob is DATE data type, you need to convert the literal to DATE using TO_DATE and the proper format model. The syntax is:
TO_DATE('<date_literal>', '<format_model>')
For example,
SQL> CREATE TABLE t(dob DATE);
Table created.
SQL> INSERT INTO t(dob) VALUES(TO_DATE('17/12/2015', 'DD/MM/YYYY'));
1 row created.
SQL> COMMIT;
Commit complete.
SQL> SELECT * FROM t;
DOB
----------
17/12/2015
A DATE data type contains both date and time elements. If you are not concerned about the time portion, then you could also use the ANSI Date literal which uses a fixed format 'YYYY-MM-DD' and is NLS independent.
For example,
SQL> INSERT INTO t(dob) VALUES(DATE '2015-12-17');
1 row created.
date must be insert with two apostrophes'
As example if the date is 2018/10/20. It can insert from these query
Query -
insert into run(id,name,dob)values(&id,'&name','2018-10-20')
let suppose we create a table Transactions using SQl server management studio
txn_id int,
txn_type_id varchar(200),
Account_id int,
Amount int,
tDate date
);
with date datatype we can insert values in simple format: 'yyyy-mm-dd'
INSERT INTO transactions (txn_id,txn_type_id,Account_id,Amount,tDate)
VALUES (978, 'DBT', 103, 100, '2004-01-22');
Moreover we can have differet time formats like
DATE - format YYYY-MM-DD
DATETIME - format: YYYY-MM-DD HH:MI:SS
SMALLDATETIME - format: YYYY-MM-DD HH:MI:SS
insert into run(id,name,dob)values(&id,'&name',[what should I write
here?]);
insert into run(id,name,dob)values(&id,'&name',TO_DATE('&dob','YYYY-MM-DD'));
You can also use the "timestamp" data type where it just needs "dd-mm-yyyy"
Like:
insert into emp values('12-12-2012');
considering there is just one column in the table...
You can adjust the insertion values according to your table.
I simply wrote an embedded SQL program to write a new record with date fields.
It was by far best and shortest without any errors I was able to reach my requirement.
w_dob = %char(%date(*date));
exec sql insert into Tablename (ID_Number ,
AmendmentNo ,
OverrideDate ,
Operator ,
Text_ID ,
Policy_Company,
Policy_Number ,
Override ,
CREATE_USER )
values ( '801010',
1,
:w_dob,
'MYUSER',
' ',
'01',
'6535435023150',
'1',
'myuser');
To insert the current date you can just use this GETDATE() function.
insert into run(id,name,dob) values(&id,'&name',GETDATE());
you can also use CURRENT_TIMESTAMP() function to insert current date and time.

Using CURRENT_TIMESTAMP result to insert in an INSERT INTO statement

I was trying to execute the following query:
DECLARE #MyValue DATETIME
SET #MyValue = CAST((SELECT CURRENT_TIMESTAMP) as DATETIME)
INSERT INTO Person (Gender,Name, JoinDate)
VALUES ('M','Alfred',#MyValue)
but SQL Server keeps throwing the following error:
Msg 241, Level 16, State 1, Procedure Insert_Current_Time, Line 8
Conversion failed when converting date and/or time from character
string.
I've already tried many other things, but none of them seemed to solve it. Is there any solution for this?
Just do this:
INSERT INTO Person (Gender,Name, JoinDate)
VALUES ('M','Alfred',getdate())
or this:
INSERT INTO Person (Gender,Name, JoinDate)
VALUES ('M','Alfred',current_timestamp)
Can you put the CURRENT_TIMESTAMP into your insert and dispense with the cast?
This works for me:
create table flar ( thetime datetime);
insert into flar values( CURRENT_TIMESTAMP);
Is JoinDate a string/varchar datatype? If so you need to cast it to a string instead of trying to store a datetime value in a string field.
Check this out: How to convert DateTime to VarChar