How to add 1 day from a user defined date in SQL? - sql-server

What I understood in SQL is if you add 1 day from today's date, you can use
SELECT #date = CONVERT(VARCHAR(8), DATEADD(DAY, 1, GETDATE()), 112)
but my issue is, I am not getting today's date. I have a user defined field for date which I was the one who set this date.
Example: my column is name is "Return Booked", how shall I add 1 day to every return booked I have set?
See attached: SQL Server result
Also, if I try to use CONVERT (DATEADD, *****) I have an error below:
How to deal with the error: Conversion failed when converting date and/or time from character string.
My current SELECT statement is
SELECT dbo.AdditionalDetailInfo.UserDefined6 AS ReturnBooked
Note that the data type of UserDefined6 is nvarchar. :(
Thank you!

You need to change the GETDATE() in the snippet to your value, and it is not a good practice to keep date values in nvarchar, so you will need some conversion first.
something like that:
SELECT CONVERT(VARCHAR(8), DATEADD(DAY, 1, (CONVERT(DATETIME,UserDefined6))),112) AS ReturnBooked
FROM dbo.AdditionalDetailInfo

As datatype of your column is nvarchar, Dateadd function on nvarchar will fail, so First you need to convert the column value to datetime and then use the DateAdd function, like below
Select DATEADD(DAY, 1, CONVERT(Datetime,ReturnBooked))
After looking at the image of sample data, it seems you have a row with date text in wrong format 08/010/2018. The conversion will fail for this particular row, so recommended to fix such bad data.

Related

T SQL Conversion failed when converting date and/or time from character string from VARCHAR(MAX)

I'm using SQL Server 2014. I have a date stored as varchar(MAX) in the format of:
2019-02-18
However, I want it in the British format dd/mm/yyyy (103).
This is my SQL:
SELECT CONVERT(DATE, DateField, 103) AS "JobStartDate"
FROM tblTest
However, I keep getting this error:
Conversion failed when converting date and/or time from character string.
What am I missing?
Update: The date is initially stored as varchar max as it is coming from a 3rd party system. I have no control over this and I completly understand this is the wrong format, but this is what I have been given.
I have a date stored as varchar(MAX)
There's your problem right there.
Not only you are using the wrong data type to store dates, you are also using max which is a known performance killer.
The solution to the problem is to alter the table and store dates in a Date data type - but first, you must look up all the objects that depends on that column and make sure they will not break or change them as well.
Assuming this can't be done, or as a temporary workaround, you must first convert the data you have to Date, and then convert it back to a string representation of that date using the 103 style to get dd/mm/yyyy.
Since yyyy-mm-dd string format is not culture dependent with the date data type, you can simply do this:
SELECT CONVERT(char(10), TRY_CAST(DateField As Date), 103) As [JobStartDate]
FROM tblTest
Note I've used try_cast and not cast since the database can't stop you from storing values that can't be converted to dates in that column.
You want to format the DateField column and not convert it to date.
So first convert it to DATE and then apply the format:
SELECT FORMAT(CONVERT(DATE, DateField, 21), 'dd/MM/yyyy') AS JobStartDate
See the demo.

How to add an hour in timestamp in sql server (without Declare)

I want to add an hour in the parameter TimeStamp, but not with declare parameter i.e
DECLARE #datetime2 datetime2 = '2019-03-01T09:25:21.1+01:00'
SELECT DATEADD(hour,1,#datetime)
I have a column name TimeStamp in a table and i want to add in all data plus 1 hour.
The column
TimeStamp
2019-03-01T09:25:20.1+01:00
2019-03-01T09:25:21.1+01:00
2019-03-01T09:25:19.1+01:00
I try something like this
SELECT DATEADD(hour,1, TimeStamp), but i have an error
Conversion failed when converting date and/or time from character
string.
Any possible answers ??
Thanks
SELECT DATEADD(hour,1, TimeStamp) is correct
However, The format in TimeStamp is wrong,
So, cast it to DateTime2 First
CAST(TimeStamp as DateTime2)
OR
CAST('2019-03-01T09:25:20.1+01:00' as DateTime2)
So,
SELECT DATEADD(hour, 1, CAST(TimeStamp as DateTime2))
Conversion failed when converting date and/or time from character
string.
The error message means that column TimeStamp stored as a string. DATEADD expects a valid value that is date/datetime/datetime2 or can be converted into it from a string. Because a sample value look like DATETIME2, such extra conversion perhaps is needed:
SELECT DATEADD(hour,1, CAST(TimeStamp as datetime2))
Your syntax will be fine as defined.
It might be a value in your column that is not able to parse to datetime2 because it contains an invalid character.
You could add the ISDATE() to the expression to check if it is valid.
https://learn.microsoft.com/en-us/sql/t-sql/functions/isdate-transact-sql?view=sql-server-2017
edit: forgot to mention you could parse before adding with try_cast or try_convert to datetime2
In Your Timestamp +01:00 represents the Time offset to GMT. You can convert this to your local time and then Add the Hours using DATEADD()
or Remove the Time Offset from the string and add one hour using DATEADD() As suggested by Others.
According to this https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql?view=sql-server-2017#date-and-time-styles
you have to convert the timestamp with timezone using type 127.
127 is the input format for:
ISO8601 with time zone Z.
yyyy-mm-ddThh:mi:ss.mmmZ (no spaces)
Note: For a milliseconds (mmm) value of 0, the millisecond decimal value will not display. For example, the value '2012-11-07T18:26:20.000 will display as '2012-11-07T18:26:20'.
select convert(datetime2, '2019-03-01T09:25:20.1+01:00', 127)
if you are not using convert and the 127 by using cast you may run in conversion problems depending on language settings of the users.
Maybe you are after this?
select dateadd(hour,1,convert(datetimeoffset, TimeStamp))
Best to not store dates and times as text though.
Edit: Note that his will retain your time zone information if that is important to you.

Importing date column ends in error

While i try to upload a flatfile which contains date fields with data type DATE in ssms import/export wizard throws an error like below
Conversion failed when converting date and/or time from character string
Actual data in flat file
Period
12/17/2003
01/01/0001
10/25/2001
01/01/0001
Please help me how to upload those dates ..... i know error which lies in fileds which contains '01/01/0001' but it is business logic i cant able to change those data.... !!!
Thanks in advance
In your case, One possibility to convert the Date in integer(37972) to DATETIME after the insertion is by using dateadd.
Run the below query, after you Insert the values into VARCHAR type column.
UPDATE YourTableName
SET ColumnWithVarcharType = CAST(DATEADD(d,
CAST(ColumnWithVarcharType AS INT), -2) AS VARCHAR(20))
WHERE IsNumeric(ColumnWithVarcharType) = 1
Above query will update only the selected values having integer(37972) value. It won't care about values like '01/01/0001'.
SELECT DATEADD(d, 0, 0) => 1/1/1900
SELECT DATEADD(d, 37972, -2) => 12/17/2003
by default the DB return the initial date used in the sql server for the query SELECT DATEADD(d, 0, 0). In the same way you can add the 37972 to the Initial date like SELECT DATEADD(d, 37972, -2).
Try using ISDATE function which will tell you whether the given date is Valid or not.
SELECT CASE
WHEN Isdate('10/25/2001') = 1 THEN CONVERT(varchar(20), '10/25/2001',102 )
ELSE NULL
END
The problem is with your input value: => 01/01/0001
Immediate Workaround i can suggest is change your datatype in table from datetime to date
select cast('01/01/0001' as date)
or
select convert(date,'01/01/0001')
Output: 0001-01-01
select cast('01/01/0001' as datetime)
or
select convert(datetime,'01/01/0001')
Output: Msg 242, Level 16, State 3, Line 1
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.

Compare dates in MS SQL using Convert

I want to do the correct way to get a date from a #parameter that contains the complete datetime, that user gets from a calendar from TFS File.
In the select I would want to use something like CONVERT(varchar(10), #FechaHasta.Value, 120) AS DATE01 and then get the only date, throwing out the time from the parameter.
For the next step, I would want to compare it with another date in WHERE clause, having this code :
Then, I would want to make this work on for looking for between two dates, and the last one, throwing out the time from the datetime.
Thanks.
I am assuming #FetchHasta is a datetime
CONVERT(VARCHAR(10), #FetchHasta, 101)
is what gets you just the date part. i.e. 10/28/2014 1:10 PM would simply become 10/28/2014.
Source
EDIT: Alternatively, How to return the date part only from a SQL Server datetime datatype

SQL Server 2008 script - how to to acquire current date from system and store it into a date column

Hey fellas, I'm having difficulty obtaining only the date from the system and inserting it into a column, is there a built-in function that can acquire it?
On top of that, how do I add years to the current date?
I know I'm pushing it right now, but I'm also wondering what's the format for the date datatype?
Because sometimes I'd like to manually insert values into a column with that type in mind.
Any help would greatly be appreciated.
Thanks.
To get date only (SQL Server 2008 only) CAST to date type
SELECT CAST(GETDATE() AS date)
To add years, use DATEADD
SELECT DATEADD(year, 2, CAST(GETDATE() AS date))
Formats: use yyyymmdd or ISO yyyy-mm-dd (for newer datetime types) for safety.
Read this for everything about date+time in SQL Server
To add a year to the current date, look at the dateadd() function.
To just get the date from sql w/o the time, you can do this:
DECLARE #Date DATETIME
SELECT #Date = CONVERT(VARCHAR, GETDATE(), 101)
SELECT #Date
Sql will implicity convert the VARCHAR back to DATETIME. Look up the CONVERT function in BOL and it will give you all kinds of different styles for the 3rd parameter.
Bender

Resources