SQL Server Converting int to Date - sql-server

I have a scenario where I have an int column with the following dates for example:
20131210
20131209
What I want is, I want to convert the above to a date datatype so that I can use it with GETDATE() function.
This is my try but I am getting an error:
SELECT CONVERT(DATETIME, CONVERT(varchar(8), MyColumnName))
FROM MyTable
WHERE DATEADD(day, -2, CONVERT(DATETIME, CONVERT(CHAR(8), MyColumnName))) < GetDate()
This is the error I am getting:
Conversion failed when converting date and/or time from character string.

You have at least one bad date in your column (it could be 99999999 or 20130231 or who knows). This is what happens when you choose the wrong data type. You can identify the bad row(s) using:
SELECT MyColumnName FROM dbo.MyTable
WHERE ISDATE(CONVERT(CHAR(8), MyColumnMame)) = 0;
Then you can fix them or delete them.
Once you do that, you should fix the table. There is absolutely no upside to storing dates as integers, and a whole lot of downsides.
Once you have the date being stored in the correct format, your query is much simpler. And I highly recommend applying functions etc. to the right-hand side of the predicate as opposed to applying it to the column (this kills SQL Server's ability to make efficient use of any index on that column, which you should have if this is a common query pattern).
SELECT MyColumnName
FROM dbo.MyTable
WHERE MyColumnName < DATEADD(DAY, 2, GETDATE());

Try:
CREATE TABLE IntsToDates(
Ints INT
)
INSERT INTO IntsToDates
VALUES (20131210)
, (20131209)
SELECT CAST(CAST(Ints AS VARCHAR(12)) AS DATE)
FROM IntsToDates

I've had a similar problem where I need to convert INT to DATE and needed to cater for values of 0. This case statement did the trick for me
CASE MySourceColumn
WHEN ISDATE(CONVERT(CHAR(8),MySourceColumn)) THEN CAST('19000101' AS DATE)
ELSE CAST(CAST(MySourceColumn AS CHAR) AS DATE)
END
AS MyTargetColumn

Related

can we use if condition for compare 2 dates and display the row in sql server

I have 2 dates column, one is current date and the one is user define date, I have to display the specific row when the user define date is 2days greater than current date.
In the below code I try to display the row, when both dates are equal. But I don't know how display the row in sql.
I have following Columns,
Rid
DateTime (User define date and time)
Reminder
Description
CRDateTime (current date and time)
I have to set 3 condition.
if both dates are equal means that should be display,
if DateTime is 2 days before CRDate means I have to display that row,
if DateTime is 1 day before the CRdate means I have to display that row.
declare DateTime as datetime1;
select RId if CAST (DateTime as date) =CAST (#CRDateTime as date)
The IF...ELSE statement is a control-flow statement that allows you to execute or skip a statement block based on a specified condition.
For example:
IF Boolean_expression
BEGIN
-- Statement block executes when the Boolean expression is TRUE
END
ELSE
BEGIN
-- Statement block executes when the Boolean expression is FALSE
END
If you want to check something in your SQL Statements you should use the where clause.
It could be looking like:
SELECT * FROM `[YOUR_TABLE_NAME]` WHERE `DateTime` = `CRDateTime`
If you want to check the date in a 2 Day decade you can use the SQL DATEADD Function.
It lookse like:
SELECT DATEADD(day, +1, '2017/08/25') AS DateAdd;
Resault of this code is 2017/08/26
In your case it looks like this:
SELECT RId where DATEADD(day, +2, DateTime) = CRDateTime
--- EDIT SECTION: ---
EDIT 1:
All in one you can use this code here:
SELECT RId WHERE
`DateTime` = `CRDateTime` OR
DATEADD(day, +1, DateTime) = CRDateTime OR
DATEADD(day, +2, DateTime) = CRDateTime
As I understand you basically want to show all the records with in range of 2 days.
SELECT RId, DateTime, Reminder, Description, CRDateTime
WHERE CRDateTime BETWEEN DATETIME AND DATEADD(day, +2, DateTime)
Or you may try this
SELECT RId, DateTime, Reminder, Description, CRDateTime
WHERE DateTime BETWEEN DATEADD(day, -2, CRDateTime) AND CRDateTime
The question isn't clear. I assume the actual question is how to filter a table's rows between two dates.
Filtering in SQL (in any product) is the job of the WHERE clause, not IF. You can use the BETWEEN clause to select values in a range.
If both the table field and the query parameter are date variables, the query is easy :
CREATE TABLE table1
(
RId int PRIMARY KEY,
DateField date,
INDEX IX_Table1_Date (DateField)
)
declare #dateParam date='20190801';
SELECT RId
FROM table1
WHERE DateField BETWEEN dateadd(day,-2,#dateParam) AND #DateParam
This query will take advantage of the IX_Table1_Date index to speed up the search. Typically, applying any kind of function on a table field prevents the query engine from using any index that includes that field simply because the values stored in the index have no relation to the function's result.
If you use the date parameter to be the current date, just assign GETDATE() to it.
declare #dateParam date=GETDATE();
If the field isn't a date, you can cast it to date and still get a fast range query, because the query engine is fast enough to convert the cast to a range query.
SELECT RId
FROM table1
WHERE cast(DateField as date) BETWEEN dateadd(day,-2,#dateParam) AND #DateParam
If DateField is not a date-related type, eg it's a varchar, a) that's a serious bug and b) the server won't be able to use any indexes.
Casting the parameter values won't affect performance as they actual values are calculated before the query starts executing. The query becomes quite noisy though :
declare #dateParam datetime='20190801'
SELECT RId
FROM table1
WHERE cast(DateField as date)
BETWEEN dateadd(day,-2,cast(#dateParam as date)) AND cast(#DateParam as date)
That's why it's better to use the correct type for parameters

Convert to mm/dd/yyyy and select max value

Using SQL Server 2014, I have a date field named LAST_BASELINE_UPDATE_DATE that is stored as datetime.
I used the CONVERT function to convert to mm/dd/yyyy:
convert(date,LAST_BASELINE_UPDATE_DATE,101) as BASELINE_UPDATE_DATE
What I want to be able to do is then select the MAX value of BASELINE_UPDATE_DATE without creating a table. Is this even possible?
It's a little unclear from your post what your data is and what you're trying to get out. Here are a couple solutions, hopefully one of which is applicable
Assuming you want your result as a string formatted mm/dd/yyyy you can do this
select convert(varchar(10), max(LAST_BASELINE_UPDATE_DATE), 101))
from YourTable
If you just need it as a date, just do
select max(LAST_BASELINE_UPDATE_DATE)
from YourTable
if LAST_BASELINE_UPDATE_DATE is already a string (formatted mm/dd/yyyy) and you want it as a date,
select max(convert(date, LAST_BASELINE_UPDATE_DATE, 101))
from YourTable
I think you are complicating this. Just do the conversion on the max datetime values.
declare #table table (LAST_BASELINE_UPDATE_DATE datetime)
insert into #table
values
('20160701 12:21'),
('20160705 03:21'),
('20160401 19:21'),
('20161201 04:21')
select
convert(varchar(10),max(LAST_BASELINE_UPDATE_DATE),101)
from
#table
This method converts your single returned row, which is the max() value of your datetime columns, as opposed to converting every row and then finding the max value.

Converting String to Int in SQL Server

I have column Terms in my table and it contains data like this:
30D, 40D, etc.
D represents days.
My question: how can I sum date in Terms column? How can I convert string to int?
Thank you in advance.
Just use REPLACE to ditch the D and CONVERT to convert the varchar to a number....
SELECT SUM(CONVERT(int, REPLACE(Terms,'D',''))) FROM TableName
Edit: Commentor is right, CAST would work too.
And I dont get all the down votes. The guy's just asking a SQL question.
Jeez... Tough crowd.
Edit2:
OK, based on comments, it seems like you would like to get a "due date" from the terms (say, TODAY + 30D or "today + 30 days"). To do that, we'd need a DATE column. OR, we can just use today's date (GETDATE())
Assume your table has a date column called ... dt
The SQL to pull dt+'30D' would require us to add 30 "days" to dt.
DATEADD will add days, and the aforementioned CONVERT+REPLACE combo will convert '30D' to just plain '30' ...
So, you end up with the following SQL:
SELECT DATEADD(day, CONVERT(int, REPLACE(Terms,'D','')), dt) FROM TableName
The 'day' tells DATEADD to add days (that seems really obvious ... now),
the CONVERT+REPLACE tells it how many days to add
AND - dt is our column name.
SO - how about just adding "30D" to TODAY? Easy. We just swap out dt with GETDATE() ...
SELECT DATEADD(day, CONVERT(int, REPLACE(Terms,'D','')), GETDATE()) FROM TableName
SELECT AVG(SALARY) - AVG(CONVERT(int, REPLACE(SALARY,'0','')))
FROM EMPLOYEES;

Convert varchar to Date, not work with AND in WHERE Clause

I have a SQL Server table Companies which contains a column UserDefined4 of type nvarchar(100).
This column contains some text plus a date in the format DD.MM.YYYY
I want to select the records in the month of March and April 2014.
I am running this query,
SELECT
(Right(Companies.UserDefined4, 10))
FROM
Companies
WHERE
(Right(Companies.UserDefined4, 10) not like '%[^0-9.]%'
AND (Right(Companies.UserDefined4, 10) not like ''))
AND (CONVERT(Date,Right(Companies.UserDefined4, 10),104) >= '2014-03-01'
and
CONVERT(Date,Right(Companies.UserDefined4, 10),104) <= '2014-04-30')
This query throws an error
Error converting a string to a date and / or time.
I have checked one by one all the records and they contains date in proper format. The strange thing for me is that the same query runs if I put OR instead of AND in following part, in the same query:
(
CONVERT(Date,Right(Companies.UserDefined4, 10),104) >= '2014-03-01'
OR
CONVERT(Date,Right(Companies.UserDefined4, 10),104) <= '2014-04-30'
)
I know, its not a wise decision to save date as a NVarChar but I have to work with this data. I am not the one who designed this database.
I've had similar problems in the past and they were all due to some of the columns not ending with the expected characters (dates in your case) and the "guard clauses" (in your case the 1st two conditions in the WHERE) not stopping the query engine from applying the "range conditions" (in your case, the last two conditions in the WHERE).
Note that I don't know exactly why that happens (maybe query optimization, no "short-circuit" evaluation or the order in that the evaluation occurs isn't what we expect -- this is me speculating), but I've noticed that if you store an intermediate result of the query (with only the "guard clauses" applied) in a temporary structure (a table variable for example) and then apply the "range clauses" to that interim result, it'll work.
For example, this will work even if there are "bad" rows (rows that don't end in a date):
DECLARE #t TABLE (userdate CHAR(10))
INSERT #t
SELECT RIGHT(Companies.UserDefined4, 10)
FROM Companies
WHERE RIGHT(Companies.UserDefined4, 10) NOT LIKE '%[^0-9.]%'
AND RIGHT(Companies.UserDefined4, 10) <> ''
SELECT *
FROM #t
WHERE CONVERT(DATE, userdate, 104) >= '2014-03-01'
AND CONVERT(DATE, userdate, 104) <= '2014-04-30'
You can check a fiddle demonstrating the issue here.
Can you be sure that UserDefined4 really always contains a date in that format in the right-most 10 characters?
If so, you could create a computed column like this:
ALTER TABLE dbo.Companies
ADD DateFromUD4 AS CONVERT(DATE, RIGHT(UserDefined4, 10), 104) PERSISTED
and then the query becomes really simple:
SELECT
(list of columns)
FROM
dbo.Companies
WHERE
DateFromUD4 >= '20140301' AND
DateFromUD4 <= '20140430'
I like to use the ISO-8601 format (YYYYMMDD without any dashes) for specifying dates as string since this is guaranteed to work on any SQL Server regardless of the date and language settings.
Since the conversion goes to a DATE, you won't have to worry about time portions either - this is a date-only computed column. This works in SQL Server 2008 and newer.

how to match datetime column by passing date only in SQL Server

I have a Table, where there is a datetime Column, I want to match this column by passing only date & datetime column is heaving date & time both (i.e 25/06/2013 4:54:12 PM).
It's usually best in this situation to leave the column alone and do some manipulation on your parameter. So if you're passing a #SearchDate parameter, I'd do:
SELECT abc from mytable
where
datetimecolumn >= #SearchDate and
datetimecolumn < DATEADD(day,1,#SearchDate)
I believe that, if you're running on SQL Server 2008 or later, and use the following:
SELECT abc from mytable
where
CAST(datetimecolumn as date) = #SearchDate
That an index on datetimecolumn can be used. Whereas I'm certain that an index is usable given my first query. You should, in general, be wary of calling functions on columns - such actions can often cripple performance by forcing a full table scan.
And unlike you're accepted answer, I would always seek to avoid treating dates as strings - as soon as you do, you're inviting all kinds of issues around formatting.
datetime format in t-sql is a little tricky, first of all you need to be aware of date time (i.e 25/06/2013 4:54:12 PM) is greater than 25/06/2013 , so you need to use > and < operators, for ![enter image description here][1]example orderdate > '20130625' AND orderdate < '20130626' , sql server considers 'YYYYMMDD' as global datetime format and it is language independent. take a look at the attachement...
try -:
DECLARE #givenDate DATE;
DECLARE #t AS TABLE (
fld_DateTime DATETIME
)
SET #givenDate = '2013-04-24'
INSERT INTO #t ( fld_DateTime )
VALUES ('2013-04-23 14:37:59.580')
, ('2013-04-23 14:59:02.403')
, ('2013-04-23 15:15:36.890')
, ('2013-04-24 08:57:45.800')
, ('2013-04-24 10:44:56.663')
, ('2013-04-24 13:18:20.760')
, ('2013-04-25 09:38:55.503')
, ('2013-06-28 09:20:11.007')
, ('2013-06-28 12:37:04.973')
, ('2013-06-28 12:38:50.130')
, ('2013-07-03 15:27:36.167')
SELECT fld_DateTime
FROM #t
WHERE fld_DateTime >= #givenDate AND fld_DateTime < DATEADD(DAY, 1, #givenDate)
You can use CAST and CONVERT functions for converting date
http://msdn.microsoft.com/en-us/library/ms187928(v=sql.105).aspx
For example
select *
from datetimetable
where convert(char(10), datetimecolumn, 103) = '25/12/2013'
BUT remember, that this code is for testing purposes only.
I recommend you to play with different parameters of CONVERT function
in order to better understand it (and to play with different sizes of the first parameter)
please, view solutions in the other answers on your question to find out the best one for your environment

Resources