GetUtcDate in insert statement in SQL Server - sql

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.

Related

syntax error when trying to input date and time

I just started with SQL and I'm having a problem when trying to insert an date and time.
The table structure:
CREATE TABLE Voo_Pac
(
codReserva INT NOT NULL PRIMARY KEY,
DataCont DATE,
HoraCont TIME
);
Code I'm trying to use to insert date and time:
INSERT INTO Voo_Pac (codReserva, DataCont, HoraCont)
VALUES (1), (15-08-2019), (12:13:52);
When I try to execute the code, it gives me the following message:
Error 1: could not prepare statement (1 near ":13": syntax error)
I assume you are using MySQL/MariaDB/SQL Server because of the TIME datatype?
Your insert should be
INSERT INTO Voo_Pac (codReserva, DataCont, HoraCont)
VALUES (1, '2019-08-15', '12:13:52');
see demo
You at least need quotes. And depending on your DB maybe a CAST to the apropiated type
INSERT INTO Voo_Pac (codReserva, DataCont, HoraCont)
VALUES 1, '15-08-2019', '12:13:52';

Issues with TIMESTAMP and CURRENT_TIMESTAMP in SQL commands

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;

Conversion failed when converting date and/or time from character string SQL

CREATE TABLE TICKET
(
TicketID int primary key,
StartLoc varchar(20),
FinalLoc varchar(20),
price int,
DateOfPurchase date,
SeatNumber int,
TrainID int,
DepartureDate date ,
);
insert into TICKET
values (1,'HaydarPasa','Sirkeci',20,'20,18-06-12 10:34:09 AM',10,1,'20-06-12 10:34:09 AM')
I'm using SQL Server Management 2008 R2 version.When execute the query it says
Conversion failed when converting date and/or time from character string SQL
#juergenD is right, the string 20,18-06-12 10:34:09 AM is not a date string. Is the 20 part of the insert? if so your table definition is off. I expect a copy-paste error here...
Additionally: When i try your query on my machine, it still gives an error converting to date. If I change the dates to the format yyyy-MM-dd hh:mm:ss AM it does work. Might be to do with local settings though.

Revert CAST(0xABCD AS date)

I am designing a query to build an insert query from parts of the data that is in a database.
I know that you can export the whole database using SQL Server Management Studio, but I only need a part, and I need it in an automated form.
The Insert query that SSMS generates for a certain dataset would be
INSERT INTO tbl (dateCol) VALUES(CAST(0xABCD AS Date))
GO
and I am now trying to cast the date inserted by this statement back to 0xABCD.
I don't know what type 0xABCD is, so I played around:
Casting to int returns Explicit conversion from data type date to int is not allowed error
Casting to string returns ISO format, but not 0xABCD format.
Could I use ISO format from casting to string? If so, why did MS choose to use some kind of hex values with CAST, instead of universally understandable ISO date, in its own SSMS export routine?
SELECT CAST(CAST(0xABCD AS INT) AS DATETIME)
-- 2020-06-01 00:00:00.000
SELECT CAST(CAST(CAST('2020-06-01 00:00:00.000' AS DATETIME) AS INT) AS BINARY(2))
-- 0xABCD

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