Using CURRENT_TIMESTAMP result to insert in an INSERT INTO statement - sql

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

Related

How to insert a cast conversion into database

I've been trying to insert a varchar value into a table in SQL using a cast.
The varchar input values has a string datetime format like this:
'08/25/2022 03:34:59 PM'
The fechaInicio column is originally filled with NULL, and the purpose of the stored procedure is to update that column with the #strDateTime value sent.
Example of my table [Table_Input]:
fechaInicio
ID
NULL
2
If I just do a
SELECT CAST('08/25/2022 03:34:59 PM' AS DATETIME)
it actually works and shows me the correct casting in the message window. But the problem is when I try to update into the table.
I removed my try-except commands to see the error.
If I call the stored procedure like this
[SP_Table_Input_Get_Series] '08/25/2022 03:34:59 PM', 2
I get the following error:
Msg 241, Level 16, State 1, Procedure SP_Table_Input_Get_Series, Line 34 [Batch Start Line 13]
Conversion failed when converting date and/or time from character string
My stored procedure is something like this:
PROCEDURE [SP_Table_Input_Get_Series]
#strDateTime NVARCHAR(50),
#cId int
AS
BEGIN TRANSACTION
UPDATE [Table_Input]
SET
---fechaInicio =convert(datetime, #strDateTime, 5),
---fechaInicio = N'select cast(#strDateTime as datetime)'
fechaInicio = CAST(#strDateTime AS datetime)
WHERE id = #cId -- the where clause works fine
COMMIT TRANSACTION
All the 3 options (including commented ones in the stored procedure) didn't work.
Also a constraint is I cannot modify the column type to varchar or any other type.
I will really appreciated if someone can help me find a solution.
I'm running the stored procedure directly in Microsoft SQL Server Management Studio.
Please try the following solution.
As #AlwaysLearning pointed out, I changed 89 to 59 seconds.
SQL
-- DDL and sample data population, start
DECLARE #tbl TABLE (ID INT IDENTITY PRIMARY KEY, fechaInicio DATETIME2(0));
INSERT #tbl (fechaInicio) VALUES
(GETDATE());
-- DDL and sample data population, end
DECLARE #strDateTime VARCHAR(50) = '08/25/2022 03:34:59 PM';
-- before
SELECT * FROM #tbl;
UPDATE #tbl
SET fechaInicio = convert(DATETIME2(0), #strDateTime, 101)
where ID = 1;
-- after
SELECT * FROM #tbl;
Output
ID
fechaInicio
1
2022-08-25 15:34:59

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';

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'

ServiceStack OrmLite and DateTimeOffset support in the UK

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'