Issues with TIMESTAMP and CURRENT_TIMESTAMP in SQL commands - sql

I have some issue creating tables that use CURRENT_TIMESTAMP to specify a date. I need this because I'm using java jpa entities to retrieve them by date. If I run to a local h2 database I have no issues.
In this example:
INSERT INTO Post (id, title, slug, teaser, body, author_id, posted_on)
VALUES (1, 'Spring Boot Rocks!', 'spring-boot-rocks', #TEASER, #BODY, 1, CURRENT_TIMESTAMP);
Everything gets created and works perfectly, but when I try the same query in an Azure SQL database that I'm connecting into I get the error
Failed to execute query. Error: Cannot insert an explicit value into a
timestamp column. Use INSERT with a column list to exclude the
timestamp column, or insert a DEFAULT into the timestamp column.
If I try to change CURRENT_TIMESTAMP to TIMESTAMP I get;
Failed to execute query. Error: Invalid column name 'TIMESTAMP'.
If I change it to DEFAULT as the previous error suggests the tables get created but I can't retrieve them by date of creation since DEFAULT is not a time value.
full query
SET IDENTITY_INSERT author ON
insert into author(id,first_name,last_name,email) values (1,'Dan','Vega','danvega#gmail.com');
insert into author(id,first_name,last_name,email) values (2,'John','Smith','johnsmith#gmail.com');
SET IDENTITY_INSERT author OFF
SET IDENTITY_INSERT post ON
DECLARE #TEASER varchar(4000) = 'text...'
DECLARE #BODY varchar(4000) = 'text...'
insert into Post(id,title,slug,teaser,body,author_id,posted_on) values (1,'Spring Boot Rocks!','spring-boot-rocks',#TEASER,#BODY,1,CURRENT_TIMESTAMP);
insert into Post(id,title,slug,teaser,body,author_id,posted_on) values (2,'Spring Data Rocks!','spring-data-rocks',#TEASER,#BODY,1,CURRENT_TIMESTAMP);
insert into Post(id,title,slug,teaser,body,author_id,posted_on) values (3,'John Blog Post 1','john-blog-post-1',#TEASER,#BODY,2,CURRENT_TIMESTAMP);
insert into Post(id,title,slug,teaser,body,author_id,posted_on) values (4,'John Blog Post 2','john-blog-post-2',#TEASER,#BODY,2,CURRENT_TIMESTAMP);
insert into Post(id,title,slug,teaser,body,author_id,posted_on) values (5,'John Blog Post 3','john-blog-post-3',#TEASER,#BODY,2,CURRENT_TIMESTAMP);
insert into Post(id,title,slug,teaser,body,author_id,posted_on) values (6,'Refactoring our Spring Data Project','refactoring-spring-data-project',#TEASER,#BODY,1,CURRENT_TIMESTAMP);
SET IDENTITY_INSERT post OFF

The TIMESTAMP datatype in SQL Server (and SQL Azure) is NOT what the ISO/ANSI Standard defines (this is a leftover of the original Sybase heritage of SQL Server).
It's really just a binary counter for optimistic concurrency checking - it has NOTHING to do with a date and/or time at all!
To store and handle dates and times, use the datatype DATE (for just dates - no time) or DATETIME2(n) for date&time instead

Fixed by recreating the database using application.properties spring.jpa.hibernate.ddl-auto=create-drop and replacing
#CreatedDate #Column(columnDefinition = "TIMESTAMP")
private Date postedOn;
to
#CreatedDate #Column(columnDefinition = "DATETIME2(0)")
private Date postedOn;

Related

Inserting missing date into non nullable Datetime field

Here we have an existing database and I'm building a new system with a new database.
There I need to transfer some data from the old database table to the new database table.
I wrote this query in the SQL
INSERT INTO [Mondo-UAT].[dbo].[Countries] (
[Country_Name]
,[Country_Code]
,[Note]
)
SELECT [Code1]
,[Code3]
,[Name]
FROM [MondoErp-UAT].[dbo].[Nations]
The issue is in the [Mondo-UAT].[dbo].[Countries] table has other columns like Note is a string and Status is a bool CreateBy is int CreateDate is DateTime . So when I run the query it returns with an error
Msg 515, Level 16, State 2, Line 8 Cannot insert the value NULL into column 'CreatedDate', table 'Mondo-UAT.dbo.Countries'; column does not allow nulls. INSERT fails. The statement has been terminated
So I wanna know how to insert data for the CreateDate,CreateBy ,Notes from the above script I wrote.
If the target table has non-nullable columns without defaults, you have to specify values for those fields when inserting data.
The easiest solution would be to modify the target table to add DEFAULT values for those fields, eg SYSDATETIME() for Created, SYSTEM_USER for CreatedBy and '' for Notes. For Status you'll have to decide what a good default status is. 0 may or may not be meaningful.
Otherwise, these values will have to be specified in the query:
INSERT INTO [Mondo-UAT].[dbo].[Countries] (
[Country_Name]
,[Country_Code]
,[Note]
, Created
, CreatedBy
, Status
)
SELECT [Code1]
,[Code3]
,[Name]
, SYSDATETIME()
, SYSTEM_USER
, 0
FROM [MondoErp-UAT].[dbo].[Nations]
SYSTEM_USER returns the login name of the current user, whether it's a Windows or SQL Server login. This makes it a good default for user columns.
SYSDATETIME returns the current time as a DATETIME2(7) value. If Created is a DATETIMEOFFSET, SYSDATETIMEOFFSET should be used.
You can set Default Value for CreateDate,CreateBy,Notes columns in the [Mondo-UAT].[dbo].[Countries] table if they are not null columns. So, When you insert data into the table and do not insert a value for these columns, the default value will be inserted.

having (Conversion failed ) error in SQL Server

When I create a table using bellow SQL query:
CREATE TABLE student(studentID INTEGER PRIMARY KEY,studnetName VARCHAR (30) NOT NULL,birthday Date)
Bellow operations(SQL commands) show me an error:
INSERT INTO student VALUES('226745','Ahmed','24-06-1997')
INSERT INTO student VALUES('226745','sara','28-03-2000')
INSERT INTO student VALUES('226745','Ali','12-02-2007')
the exact error is:
( Conversion failed when converting date and/or time from character string).
Can anybody help to explain why it happens?
It's because sql engine can't figure out the date format automatically (probably confused between m-d-y and d-m-y)
so you can specify the dateformat before you insert, ex in sql server:
set dateformat dmy;
and the same situation in other dbms
You don't specify your database. Most databases support strings in the format 'YYYY-MM-DD' (an ISO 8601-compatible format) for date constants:
INSERT INTO student VALUES('226745', 'Ahmed', '1997-06-24');
INSERT INTO student VALUES('226745', 'sara', '2000-03-28');
INSERT INTO student VALUES('226745', 'Ali', '2007-02-12');
In Standard SQL, date constants are supported by using the date keyword:
INSERT INTO student VALUES('226745', 'Ahmed', DATE '1997-06-24');
INSERT INTO student VALUES('226745', 'sara', DATE '2000-03-28');
INSERT INTO student VALUES('226745', 'Ali', DATE '2007-02-12');
I would also advise you to list the columns explicitly when using insert.

Why does MS SQL Server error on inserting the second row but not on the first row?

I have an SQL table that will let me insert some rows with a datetime field but not all rows and I can't see why not. The error I get is
'The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.'
To try and work this out I created a temporary table with 1 colum and tried to add the two datetimes that are causing the issue.
create table #DateTimeTest ( created datetime );
I then try inserting these two rows
insert into dbo.#DateTimeTest (created) VALUES ('2020-06-12 05:46:00.00');
insert into dbo.#DateTimeTest (created) VALUES ('2020-06-19 05:31:00.00');
The first row is inserted without any problems, the second-row errors, but I can't understand why.
(1 row affected)
Msg 242, Level 16, State 3, Line 10
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
The statement has been terminated.
Completion time: 2020-07-15T11:28:43.6451779+01:00
insert into dbo.#DateTimeTest (created) VALUES ('2020-06-19 05:31:00.00');
Apparently, your date format is YDM rather than YMD. You can fix this in several ways.
One method is to use an unambiguous date/time format. In your case, that would include a T:
insert into dbo.#DateTimeTest (created) VALUES ('2020-06-12T05:46:00.00');
insert into dbo.#DateTimeTest (created) VALUES ('2020-06-19T05:31:00.00');
The reason this works is because the YYYY-MM-DDTHH:MI:SS format is the standard format for a date/time format in SQL Server -- unambiguously and not affected by dateformat. Similarly YYYYMMDD (note: no hyphens) is the standard, unambiguous format for a date constant in SQL Server, but YYYY-MM-DD is subject to dateformat.
A second method would be to set the dateformat to YMD:
set dateformat YMD;
Here is a db<>fiddle illustrating this.
A third method would be to explicitly extract the datetime from the string, using a function such as convert() -- and perhaps a few string operations as well.

Inserting a date into a table adds extra timestamp with it

I am trying to insert a column that is in date format such like 2019-09-25 but whenever I run the query it adds the timestamp (2019-08-15T00:00:00.0000000) to it even though I have defined the column to be 'date' format. How can I make sure it only shows the date?
There are few settings which sets by Oracle on your behalf. One of them is date/time format. Your default NLS_DATE_FORMAT is currently set up to return timestamp also along with date. You only need to alter your session to return only date while fetching column with DATE datatype -
ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD';
Check like below-
-- FUNCTION for Getting Azure DateTime as per our Time Zone
CREATE OR ALTER FUNCTION dbo.udf_getdate()
RETURNS DATETIME
AS
BEGIN
DECLARE #Current_DateTime DATETIME
SELECT #Current_DateTime=SYSDATETIMEOFFSET() AT TIME ZONE 'India Standard Time' -- IST Format.(give your timezone here)
RETURN #Current_DateTime
END
GO
-- DECLARE LOCAL VARIABLE AND GET THE RESULTS AS EXPECTED AND USE IT
DECLARE #CurrentDateTime DATETIME,#CurrentDate DATE;
SELECT #CurrentDateTime = dbo.udf_getdate();
SELECT #CurrentDate = CAST(#CurrentDateTime AS DATE);
SELECT #CurrentDateTime AS [CurrentDateTime],#CurrentDate AS [CurrentDate];
I've had a lot of trouble with this, and i came to conclusion that it is working properly but the thing is that query editor on Azure portal is in preview mode.
In pictures below you can see that when I inserted a value that has some hours/minutes/sec into a column that is of type 'date'
Once I try to read the same data, hours/minutes/secs will be set to 0, which means it wrote the correct value to the table (only year-month-day), but problem comes when that value needs to be displayed.
Long story short:
Basically i think Azure portal can't display correct value because it is in preview. (but correct value is inserted into database)
in picture below is how Azure portal query editor is displaying data:
and if you export that database, and import it into a local SQL server, same data will be displayed as

GetUtcDate in insert statement in SQL Server

I need to have the current date and time inserted into SQL Server.
I tried the following method but it didn't work.
insertstatement = "insert into tablename(sqldate) values (?)"
values = ('getutcdate()')
cursor.execute(insertstatement , values)
cnxn.commit()
I am getting the following error:
[Microsoft][SQL Server Native Client 11.0][SQL Server]Conversion failed when converting date and/or time from character string. (241) (SQLExecDirectW)')
I need to use the SQL Server time only because the code is getting executed at different servers and the timezones and need to use a standard time accurate to milliseconds.
As you are trying to insert SQL datetime, then the time should be got at SQL Server, so your code should looks like this
insertstatement = "insert into tablename(sqldate) values (getutcdate())"
cur.execute(insertstatement)
cnxn.commit()
Try to use GETUTCDATE() function. Let me show an example:
insert into tablename(sqldate) values (GETUTCDATE())
In addition, your type of table column should be DateTime. For example:
DECLARE #FooTable TABLE
(
StartDate DateTime
)
INSERT INTO #FooTable
(
StartDate,
)
VALUES
(
GETUTCDATE(),
)
SELECT StartDate FROM #FooTable
MSDN has a great description about GETUTCDATE() and possible use cases.