How to convert varchar into usable date in SQL Server? - sql-server

I am having an issue converting an nvarchar into a date.
The column title is DOS and the dates are formatted like 05-03-2012.
I am trying to convert to a date so I can filter in the where clause.
I have seen explanations using CONVERT(datetime, DOS, 101) but I am not sure where this would go? In the select? In the where clause? Is this the best method to convert varchar into date?
SELECT BedSize
,avg(contributionmargin) AS ContributionMargin
FROM Summary
WHERE DOS > '06-30-2016'
GROUP BY bedsize
HAVING avg(contributionmargin) > 10000
ORDER BY contributionmargin DESC
In this example the where clause is just looking at the '06' in the date and selecting values that are greater than 06, so the results include:
07/01/2013
07/02/2009
08/31/2009
09/25/2012
11/03/2016
12/03/2008
The problem is that the years are ignored.

Option 1:
Add a new datetime column (let's suppose DOSDate) in the table and then run this query
update mytable set DOSDate = STR_TO_DATE(DOS,'%m-%d-%Y')
But future inserts in mytable will also needs to be converted and stored in DOSDate` column.
Option 2:
If you cannot add a new column, use this in where clause
select * from mytable where STR_TO_DATE(DOS,'%m-%d-%Y') > p_mydate
Since you have not provided a query, the above is a sample query to illustrate the point.
UPDATE
Initially you marked your question related to MySQL. For SQL Server you may use CAST or CONVERT instead of STR_To_DATE https://msdn.microsoft.com/en-us/library/ms187928(v=sql.90).aspx

I was able to use the convert function for SQL Server.
This code works:
SELECT BedSize
,avg(contributionmargin) AS ContributionMargin
FROM Summary
WHERE Convert(DATE, DOS, 101) > '06-30-2016'
GROUP BY bedsize
HAVING avg(contributionmargin) > 10000
ORDER BY contributionmargin DESC

Related

Creating SQL views in VBA

I am trying to create a view on a table called petients in my database. The table has five columns. One of them is the column which I want to keep patient admitted date. It data type is datetime so I want to create a query that filters the data in this table based on current date. For example I want create a view that shows only details of petients who have been recorded on the current day.
Here is my code:
CREATE VIEW [dbo].[recent petients]
AS
SELECT petient_id, name, age, contact
FROM [petients]
WHERE [date] = 'date.Today'
I am getting an error saying that failed to convert date to string. Can you help me to solve it, or where is my code wrong?
Your code looks like SQL Server code. If so, I would recommend:
SELECT petient_id, name, age, contact
FROM [patients]
WHERE [date] = CONVERT(date, GETDATE());
As a note: This version is much better than DATEDIFF() because it allows the use of an index on patient([date]).
If the "date" column has a time component, you can use:
WHERE CONVERT(date, [date]) = CONVERT(date, GETDATE())
Note that this is also index-safe in SQL Server.
I'm assuming you are using Transact-SQL from Microsoft SQL Server, but you should specify the sql dialect you are using.
Since the datetime field type generally includes also a time, it is better to use the DATEDIFF function: https://learn.microsoft.com/it-it/sql/t-sql/functions/datediff-transact-sql?view=sql-server-ver15
In your case, to consider only the record where date=today, the difference in days must be zero:
--SQL QUERY
WHERE DATEDIFF(day, GETDATE(), [date]) = 0
day identifies the element you want to consider the difference. A list of names or abbreviations can be found in the link
GETDATE() returns now datetime
2nd and 3rd arguments are the dates you want to make the difference between

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;

Select condition on date for datetime field

I want to impose date condition on a date time field in SQL Server.
The datetime field is like this 2011-01-19 17:57:18.350 and when I execute below query it yields no results.
select top 1000 *
from [dbo].[RouteState]
where convert (date, logtime, 101) = '12-01-2015'
Can someone help me what's going wrong here?
There is no need to convert the datetime column to anything. Use a closed-open interval instead and change the format of your string literal to yyyymmmdd to make sure that SQL Server will interpret the date value in the same way regardless of regional and date format settings.
select top 1000 *
from [dbo].[RouteState]
where logtime >= '20150112' and
logtime < '20150113';
For more info on casting a column to date you can have a look at Cast to date is sargable but is it a good idea?

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.

Resources