How do you update a DateTime field in T-SQL? - sql

The following query does not update the datetime field:
update table
SET EndDate = '2009-05-25'
WHERE Id = 1
I also tried it with no dashes, but that does not work either.

When in doubt, be explicit about the data type conversion using CAST/CONVERT:
UPDATE TABLE
SET EndDate = CAST('2009-05-25' AS DATETIME)
WHERE Id = 1

Normally, it should work.
But can you try this? I don't have SQL on my home PC, I can't try myself
UPDATE table
SET EndDate = '2009-05-25 00:00:00.000'
WHERE Id = 1

The string literal is pased according to the current dateformat setting, see SET DATEFORMAT. One format which will always work is the '20090525' one.
Now, of course, you need to define 'does not work'. No records gets updated? Perhaps the Id=1 doesn't match any record...
If it says 'One record changed' then perhaps you need to show us how you verify...

Using a DateTime parameter is the best way.
However, if you still want to pass a DateTime as a string, then the CAST should not be necessary provided that a language agnostic format is used.
e.g.
Given a table created like :
create table t1 (id int, EndDate DATETIME)
insert t1 (id, EndDate) values (1, GETDATE())
The following should always work :
update t1 set EndDate = '20100525' where id = 1 -- YYYYMMDD is language agnostic
The following will work :
SET LANGUAGE us_english
update t1 set EndDate = '2010-05-25' where id = 1
However, this won't :
SET LANGUAGE british
update t1 set EndDate = '2010-05-25' where id = 1
This is because 'YYYY-MM-DD' is not a language agnostic format (from SQL server's point of view) .
The ISO 'YYYY-MM-DDThh:mm:ss' format is also language agnostic, and useful when you need to pass a non-zero time.
More info : http://karaszi.com/the-ultimate-guide-to-the-datetime-datatypes

UPDATE TABLE
SET EndDate = CAST('2017-12-31' AS DATE)
WHERE Id = '123'

If you aren't interested in specifying a time, you can also use the format 'DD/MM/YYYY', however I would stick to a Conversion method, and its relevant ISO format, as you really should avoid using default values.
Here's an example:
SET startDate = CONVERT(datetime,'2015-03-11T23:59:59.000',126)
WHERE custID = 'F24'

That should work, I'd put brackets around [Date] as it's a reserved keyword.

Is there maybe a trigger on the table setting it back?

Related

Put a date variable in quotes in SQL

I have declared a variable that is getting date from an output activity.
vGetDate= 2021-03-20 and want to use this value in my query to fetch the record after that date. eg: (Select * from ABC where UpdatedDate > vGetDate) . I want to put single quotes to date in order to make it work properly.
Below is my code
declare #date1 varchar(20) = activity.output i.e will return o/p in this format(without quotes) : 2021-03-22
select *
from abc
where format([UpdatedDtTm],'yyyy-MM-dd') > cast(#date1 as datetime).
I am using this but since date1 variable has date without quotes , thats why this where condition is not working fine.
Implied data conversions inside a where clause can be a significant performance and/or reliability issue and should be avoided.
As I don't know anything about the activity.output(2021-03-22) or why you cannot use activity.output('2021-03-22') let's try to consider a simplified case. On the assumption that the column [UpdatedDtTm] is indeed a datetime column, then you can compare that column to a datetime variable without needing format() or cast(), like this:
declare #Date1 datetime = '20210322'
select * from abc
where [UpdatedDtTm] > #Date1
Keep in mind that any date related data types are NOT stored "in a format" they are actually numeric and any format that we use to understand the date or time is applied rather like typing 44279 into an Excel cell and then formatting it to a date which displays as 2021-03-24 (if your default date format is yyyy-mm-dd). It's not exactly the same in SQL Server but quite similar.
I am ignoring activity.output but assuming it is a string. Likewise I am assuming [UpdatedDtTm] is a datetime column.
declare #Date1 datetime = try_cast(activity.output as datetime)
select * from abc
where [UpdatedDtTm] > #Date1
or
declare #Date1 datetime = try_convert(datetime,activity.output,121)
select * from abc
where [UpdatedDtTm] > #Date1
Note that try_cast or try_convert will not fail if the activity.output isn't a valid date but they will return NULL in such cases and your query will return no rows.
Once you have passed the value into #Date1 then you just compare datetime column to datetime variable. Try to ignore anything to do with "format"

Find records with specific date format

I want to select all records that are not in format yyyy-mm-dd. Datatype of column is varchar.
Update the records in step 1 with the correct format(yyyy-mm-dd).
I have tried filtering with function: IsDate() but got no success.
Create table
CREATE TABLE #tempdate (dateCol varchar(50));
INSERT INTO #tempdate VALUES
('2019-05-13 16:55:47:284'),
('2019-04-05 14:08:10.060'),
('6/19/2018 12:35:53 PM'),
('2019-05-13');
Use try_cast()
select try_cast(datecol as date)
You can try below -
update #tempdate set datecol=format(cast(dateCol as date),'yyyy-mm-dd')
The most important answer was given by EzLo in a comment above: Do not store date/time values in a string format.
A native date/time type is stored in a non-readable, binary pattern. Any action will be faster and secure against culture dependency.
The readable format is something for the output only and should be done in exports or within your presentation layer.
If you have to stick with this (or if this is your attempt to clean and transform your data to a correct format), I'd suggest one of those:
SELECT *
FROM #tempdate
--either use a text base pattern
WHERE LEFT(dateCol,10) NOT LIKE '[1,2][0-9][0-9][0-9]-[0,1][0-9]-[0-3][0-9]';
--or use a fixed conversion format (here I use 126 for ISO8601)
WHERE TRY_CONVERT(date,dateCol,126) IS NULL
1.
SELECT * FROM #tempdate
WHERE ISDATE(dateCol)= 1 AND CHARINDEX('-',dateCol) = 5
2.
UPDATE #tempdate
SET datecol = CONVERT(DATETIME,datecol,102)
WHERE ISDATE(dateCol)= 1
SELECT * FROM #tempdate
Please Try the below.
update #tempdate set datecol=Convert(char(10),convert(datetime,datecol,120),126)
Please let me know
Thanks

SQL Server - Value passes ISDATE() but fails to CAST as DATE or DATETIME

I have a varchar column in my database table, on the row I would like to return it is populated as '2018-12-26T00:00:00.000' (quotes mine, not included in actual value). When I try to query for this value whenever it is a valid date, e.g.
SELECT
myValue
FROM
myTable
WHERE
ISDATE(myValue) = 1
it returns properly. However, I need this value to be converted to DATE. When I try something like this:
SELECT
CAST(myValue AS DATE) AS myValueFormatted
FROM
myTable
WHERE
ISDATE(myValue) = 1
I get an error
Conversion failed when converting date and/or time from character string
Is there any other way I can convert this varchar value to Date?
UPDATE: I've noticed through trying some different things, the query seems to be fine with me using the value as a date for anything (DATEDIFF, CONVERT back to string, etc.) in the select portion, but trying to do anything with it in the WHERE clause causes the error. To ensure nothing else is interfering, I created a temp table with only 1 row with the data value above, and running the query just against that one value gives the error
UPDATE 2: Ok, I have no idea why this fixes it, but this is what I found. When I run
SELECT
myValue
FROM
myTable
WHERE
TRY_CONVERT(DATE, myValue) IS NOT NULL
it returns EXACTLY the same values as
SELECT
myValue
FROM
myTable
WHERE
ISDATE(myValue) = 1
However, when I then add AND CAST(myValue AS DATE) < GETDATE() to each WHERE clause, only the first one works. I understand why TRY_CONVERT is safer to use, I'm still not sure why it works over GETDATE()
I can't reproduce your error...
declare #dt varchar(256) = '2018-12-26T00:00:00.000'
select cast(#dt as date)
So, there must be another rogue value in there that can't be converted.
To identify what value is causing the issue on versions < 2012, run this:
SELECT
myValue
FROM myTable
WHERE
ISDATE(myValue) = 0
Note, ISDATE is deterministic only if you use it with the CONVERT function, if the CONVERT style parameter is specified, and style is not equal to 0, 100, 9, or 109.
For 2012 onward, use TRY_CONVERT
SELECT
*
FROM myTable
WHERE
TRY_CONVERT(date, myValue) IS NULL
You could also just try something like this:
SELECT CAST(LEFT(MyValue, 10) AS DATE)
If it still doesn't work, you have some formatting issues with your data.
This helped me....
CAST string as varchar(30) then cast the varchar as datetime2
CAST(CAST(REPLACE(['Timestamp' ],'''','') AS varchar(30)) as datetime2)

SQL converting Date datatype from Varchar to Date

so I'm trying to convert my date column datatype from varchar to date.
Currently my date is in d/m/yyyy format and I want to convert to standard mm/dd/yyyy
Here's the script that I'm running
update [table]
set [PERIOD]= CONVERT(varchar(20),cast([PERIOD] as date),101)
But I'm getting an error
Msg 241, Level 16, State 1, Line 1
Conversion failed when converting date and/or time from character string.
Any tips or am I stuck?
I suggest instead of updating one string date to another format of string date, that you add a new DATE or DATETIME field to store the dates properly.
ALTER [table] ADD Proper_Date DATE
GO
UPDATE [table]
SET Proper_Date = convert(date, [PERIOD], 103)
If you must, you can wrap the above in another CONVERT():
update [table]
set [PERIOD]= CONVERT(varchar(20),convert(date,[PERIOD], 103),101)
I think if you can segregate the day and month and the year by using substring or any other string functions then use the below query
update tableA
set period = convert(datetime,cast(day(1)as varchar)+'/'+cast(MONTH(1)as varchar)+'/2014',102)
Hope its works.
You may have junk value and can get the junk values by executing the following query
SELECT [PERIOD]
FROM YOURTABLE
WHERE ISDATE([PERIOD]) = 0
To avoid junk values and update the rest try the below
update YOURTABLE
set [PERIOD]= CONVERT(varchar(20),cast([PERIOD] as date),101)
WHERE ISDATE([PERIOD]) = 1
Try this.
update [table]
set [PERIOD]= CONVERT(varchar(20),CONVERT(date,[PERIOD] ,103),101)
Problem in your query is
cast([PERIOD] as date)
You cannot directly convert d/m/yyyy format to date. So use 103 style to convert

Update only Time in a mysql DateTime field

How can I update only the time in an already existing DateTime field in MySQL? I want the date to stay the same.
Try this:
UPDATE yourtable
SET yourcolumn = concat(date(yourcolumn), ' 21:00:00')
WHERE Id = yourid;
Try this:
UPDATE t1 SET DateTimeField = CONCAT(DATE(DateTimeField),' 12:34:56');
UPDATE myTable
SET myDateTime = ADDTIME(DATE(myDateTime), #myTimeSpan)
WHERE id = #id;
Documented on MySQl date functions MySQL docs
I have solved in this way:
UPDATE table
SET myDateTime = CONCAT_WS(' ',DATE(myDateTime), CURTIME())
WHERE id = #id;
Obviously you should change CURTIME() with your desired time.
UPDATE myTable
SET myDateTime = ADDTIME(myDateTime, #myTimeSpan)
WHERE id = #id;
For exact syntax of function, see this.
Try this:
UPDATE sms
SET entry_period_end_date= entry_period_end_date+INTERVAL 6 Hour
WHERE TIME(entry_period_end_date) = '06:00:00';
UPDATE `table`
SET time = ADDTIME(time, INTERVAL 13 Hour);
Well, exactly what you are asking for is not possible. The date and time components can't be updated separately, so you have to calculate the new DateTime value from the existing one so that you can replace the whole value.
MySQL DEV page shows functions like subtime and difftime
A sample code to back the time all posts in 3 hours is above:
UPDATE tablepost SET datepost = SUBTIME( datepost , '0 3:0:0' );
Note that values 0 dont alter the respective field. Take care this code, use select first to test these function.
Reference: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_subtime
Asuming you have a DATE field and TIME field and want to inject the time into the date, try this:
UPDATE mytable
SET mydatefield = ADDTIME( DATE_FORMAT(mydatefield,'%Y-%m-%d 00:00:00'), mydatefield)
WHERE myid = ...
I used ADDTIME in the following way
Earlier in my cloud server, the DateTime was set to UTC but after changing the DateTime to Asia/Kolkata ie UTC 5:30 I wanted the same to reflect in my database tables.
I wanted to update the created_at and updated_at column by 5 hours 30 minutes. I did the following
To update all the rows of the table
UPDATE
products
SET
created_at = ADDTIME(created_at, '5:30:0'),
updated_at = ADDTIME(updated_at, '5:30:0')
You can omit the WHERE condition if you want to update all the records, but since my new records were updated with proper values. So only my rows below id less than 2500 must be updated
UPDATE
products
SET
created_at = ADDTIME(created_at, '5:30:0'),
updated_at = ADDTIME(updated_at, '5:30:0')
WHERE
id < 2500;
This what helped me. I convert time to minutes firstly: 150 for 2:30 am.
UPDATE lesson SET starts_at = DATE_ADD(Date(starts_at), INTERVAL 150 MINUTE)
Minutes are enough accurate for me, though you can use other units: https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_date-add