SQL Server: Add seconds to a datetime field? - sql

This should be a softball for you SQL guys. I know I can add to an int field with something like UPDATE tblUser SET Total=(Total+2) but what is the syntax for adding seconds to a datetime field?
I'm using SQLServer 2008

UPDATE tbluser SET DateField = DATEADD(ss,numOfSeconds,DateField)
Note the first parameter "ss". This shows that you are adding seconds to the date.
Check the docs for more info.

You should look into DATEADD.
DATEADD (datepart , number , date)
or the full update syntax
UPDATE tbl SET YourDateField = DATEADD (ss, 2, YourDateField)

Related

T-SQL: date modification, only days and months

In SQL Server 2016, in one table, I want to change a date column as:
1936-12-15
1928-11-04
1940-09-18
1933-04-26
1942-08-17
To the one below, changing only months and days to 05-20, keeping only the years!
1936-05-20
1928-05-20
1940-05-20
1933-05-20
1942-05-20
I tried the following:
UPDATE [column]
SET [column] = DATEADD(mm, 5, [column])
But it added 5 months to all dates!
Please help. Thank you.
You appear to be using SQL Server:
UPDATE [column]
SET [column] = datefromparts(year(column), 5, 20);
In earlier versions of SQL Server, you can do:
UPDATE [column]
SET [column] = datename(year, column) + '0520'
This will automatically convert the string to the correct date (although you could add an explicit cast()/convert() as well).
Using FORMATMESSAGE:
UPDATE tab
SET col = FORMATMESSAGE('%i0520',YEAR(col));
DBFiddle Demo
UPDATE [Table]
SET [column] = FORMAT([column],'yyyy-05-20')

Todays date minus a number from a integer field

Im new to SQL. I have a field (ContractDays) with an integer (number of days from a datediff) and want to create a date field with a value of todays date minus the number in ContractDays field. Can you help please?
If you are using mssql. You can do this:
SELECT DATEADD(day, -ContractDays, GETDATE())
FROM Table1
MS SQL contains datetime as number value. Integer part is number of days since 1/1/1753.
So you can write
select GetDate() - ContractDays
But it is better to use DATEADD
You need to alter the table in Oracle, MySQL or MS SQL to add a new column, let's call it ContractDate.
After you have this column, you need to update it to have the correct value.
Oracle:
update Contracts
set ContractDate = (SYSDATE - ContractDays)
MySQL:
update Contracts
set ContractDate = date_add(now(), INTERVAL -ContractDays DAY)
MS SQL (courtesy to Arion):
update Contracts
set ContractDate = DATEADD(day, -ContractDays, GETDATE())

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

SQL Server 2008 - convert varchar to datetime column

I have a table with a varchar column (dateandtime) with date and time in the format dd/mm/yyyy hh:mm:ss and I need to convert it to a datetime column.
I have a temp column dateandtimetemp in the table .
Thanks
Try this:
SELECT CONVERT(Datetime, '15/05/2013 13:55:12', 104)
It should return : 2013-05-15 13:55:12.000
Try
SELECT CONVERT(VARCHAR(30),GETDATE(),113) ;
it return result in following format
15 May 2013 16:26:29:850
So then just go ahead and try it!
UPDATE dbo.YourTable
SET DateAndTimeTemp = CAST(DateAndTime AS DATETIME)
and see if it works. If your input data is really always properly defined - you should have no issues here.
This of course depends on what langauge/dateformat setting you have activated in your database - so that might be the first problem you encounter.
If you do have issues, then you can always "clean up" your input data and try again ...
Try this
SELECT CONVERT(DATETIME, '15/05/2013 11:12:13', 103)

Datetime in where clause

How can I select 12/20/2008 in where clause of sql?
The server is SQL server 2005.
select * from tblErrorLog
where errorDate = '12/20/2008'
WHERE datetime_column >= '20081220 00:00:00.000'
AND datetime_column < '20081221 00:00:00.000'
First of all, I'd recommend using the ISO-8601 standard format for date/time - it works regardless of the language and regional settings on your SQL Server. ISO-8601 is the YYYYMMDD format - no spaces, no dashes - just the data:
select * from tblErrorLog
where errorDate = '20081220'
Second of all, you need to be aware that SQL Server 2005 DATETIME always includes a time. If you check for exact match with just the date part, you'll get only rows that match with a time of 0:00:00 - nothing else.
You can either use any of the recommend range queries mentioned, or in SQL Server 2008, you could use the DATE only date time - or you could do a check something like:
select * from tblErrorLog
where DAY(errorDate) = 20 AND MONTH(errorDate) = 12 AND YEAR(errorDate) = 2008
Whichever works best for you.
If you need to do this query often, you could either try to normalize the DATETIME to include only the date, or you could add computed columns for DAY, MONTH and YEAR:
ALTER TABLE tblErrorLog
ADD ErrorDay AS DAY(ErrorDate) PERSISTED
ALTER TABLE tblErrorLog
ADD ErrorMonth AS MONTH(ErrorDate) PERSISTED
ALTER TABLE tblErrorLog
ADD ErrorYear AS YEAR(ErrorDate) PERSISTED
and then you could query more easily:
select * from tblErrorLog
where ErrorMonth = 5 AND ErrorYear = 2009
and so forth. Since those fields are computed and PERSISTED, they're always up to date and always current, and since they're peristed, you can even index them if needed.
You don't say which database you are using but in MS SQL Server it would be
WHERE DateField = {d '2008-12-20'}
If it is a timestamp field then you'll need a range:
WHERE DateField BETWEEN {ts '2008-12-20 00:00:00'} AND {ts '2008-12-20 23:59:59'}
Assuming we're talking SQL Server DateTime
Note: BETWEEN includes both ends of the range, so technically this pattern will be wrong:
errorDate BETWEEN '12/20/2008' AND '12/21/2008'
My preferred method for a time range like that is:
'20081220' <= errorDate AND errordate < '20081221'
Works with common indexes (range scan, SARGable, functionless) and correctly clips off midnight of the next day, without relying on SQL Server's time granularity (e.g. 23:59:59.997)
Use a convert function to get all entries for a particular day.
Select * from tblErrorLog where convert(date,errorDate,101) = '12/20/2008'
See CAST and CONVERT for more info
select * from tblErrorLog
where errorDate BETWEEN '12/20/2008' AND DATEADD(DAY, 1, '12/20/2008')
Use below query for clear understanding
/****** Script for SelectTopNRows command from SSMS ******/
SELECT *
FROM [dbo].[PublishedInfo]
where PublishedDate >= '2022-02-14T11:31:16.5299166+00:00'