Converting Varchar to Datetime on SQL Server - sql

SELECT SubmitDate, Type, Location, CONVERT(DATETIME, SubmitDate, 101) AS DDate
FROM Employee
WHERE (Type IN ('C', 'Q'))
AND (DDate > DATEADD(DDate, - 1, GETDATE()))
I need to get all records from the past year, SubmitDate is a varchar. I use CONVERT to convert the column to datetime. However I am getting the following error:
DDate Not recognizable dateadd option.
I tried switching the CONVERT to the following and it didn't work:
CONVERT(DATE, SubmitDate, 101)

As users have commented above, you cannot reference column aliases in WHERE clauses on your query. You can, however, use the column transformation in the WHERE clause. It isn't very efficient, but if you're using the query once or twice (IE: Not in a SSIS package or automated task) it should be alright.
SELECT SubmitDate, Type, Location,CONVERT(datetime, SubmitDate, 101) AS DDate
FROM Employee
WHERE ([Type] IN ('C', 'Q'))
AND (CONVERT(datetime, SubmitDate, 101) > DATEADD(Day, - 1, GETDATE()))
The second problem with your query is the DATEADD clause. DATEADD requires three paramaters: The datepart, the number, and the date. You have an invalid datepart, or "what part of the date are you performing the arithmetic on". DDate is not a datepart, it's a column. A datepart is values like Month, Day, Year, Week, etc.
I edited the query to set the datepart to "Day" so the clause will evaluate (using pseduocode) GETDATE()-1 Day, but you can set it to GETDATE()-1 Month, or hour. But the current psedocode expression of GETDATE()-1 DDate doesn't make sense to your SQL Server client
Refer to Microsoft documentation for more DATEADD information

Related

SQL Server error in conversion of date from string

NPD.CreatedOn is defined as a datetime datatype column (in SQL Server).
SELECT *
FROM NPDMaster NPD
WHERE DATEDIFF(MONTH, CONVERT(VARCHAR(7), NPD.CreatedOn, 126), CONVERT(VARCHAR(30), GETDATE(), 126)) <= 6
I get this error:
Conversion failed when converting date and/or time from character string.
What can I try to resolve it?
Don't use things like DATEDIFF in the WHERE on your columns, such queries aren't SARGable and thus can (will) perform poorly. If you want rows where the date is on or after the start of the month 6 months ago then do the date logic on GETDATE()/SYSDATETIME()/etc:
SQL Server doesn't have a "start of month" function, but you can use EOMONTH and then add a day:
SELECT *
FROM dbo.NPDMaster NPD
WHERE NPD.CreatedOn >= DATEADD(DAY, 1, EOMONTH(GETDATE(),-7));
You don't need to convert the datetime values to text. DATEDIFF() expects datetime values as second and third argument:
SELECT *
FROM NPDMaster NPD
WHERE DATEDIFF(month, NPD.CreatedOn, GETDATE()) <= 6
The actual reason for the error (as is explained in the documentation), is that ...DATEDIFF implicitly casts string literals as a datetime2 type.

SQL table column need to change datetime format to date

I have a column in a table with this format '2017-05-09 14:52:32.000' I would appreciate a way to convert it to a date format like MM/DD/YYYY
I have tried with:
select DATEADD(column, DATEDIFF(column, 0, getdate()), 0)
FROM table
but I get this error:
Column is not a recognized datediff option.
I've also tried another way and failed.
Please advise.
I'm assuming from the error message you reported that you're on SQL Server.
In SQL Server, the DATEADD and DATEDIFF functions take a "date part" as the first argument: YEAR, MONTH, DAY, HOUR, MINUTE, SECOND or MILLISECOND:
SELECT DATEADD(DAY, DATEDIFF(DAY, [COLUMN], GETDATE()), [COLUMN])
FROM [TABLE]
might be want what you want.
However,
SELECT CONVERT(DATE, [COLUMN]) AS [COLUMNDATE]
Might be even easier.

Subtract two dates in Microsoft SQL Server

I want to subtract 2 dates in MS SQL Server.
Example:
Current date Last used date
'2016-03-30' '2015-02-03'
Current date refers to today's date, "Last used date" is a measure.
How to write a query in SQL Server?
I have this but doesn't work (it says "Operand data type is invalid for subtract operator")
select
CONVERT(DATE, GETDATE()) - CONVERT(DATE, LastUsedDate)
from
databasename
SELECT DATEDIFF(day,'2014-06-05','2014-08-05') AS DiffDate
Output DiffDate 61
More practice please refer below W3 school:
https://www.w3schools.com/sql/func_sqlserver_datediff.asp
Here you don't have to cast GETDATE() to date, as it is already datetime datatype. So your query will be as follows
SELECT DATEDIFF(day,CAST(LastUsedDate as date),GETDATE()) AS DifferneceDays
FROM TableName
The normal function to use is datediff():
select datediff(day, cast('2016-02-03' as date), cast('2016-03-30' as date))
You can subtract datetime values, but not dates. Alas.

Is there an equivalent to sysdate-1/24 in SQL server?

I've tried looking around for this but I can't find an answer that seems to work with the code I'm using. Basically, the below query searches on any result from the current date. I'm trying to make it so it will search only on the last hour.
In oracle I could do this using sysdate-1/24, is there a simple equivalent within SQL server? Bearing in mind I'm already using cast to get the current sysdate.
Select distinct m_record_server
from search_recording_file1
where tr_date_recorded >= cast(convert(varchar(10), getdate(), 110) as datetime)
and m_record_server is not null
You can use:
getdate() - 1.0/24
SQL Server allows you to use such arithmetic on datetime.
The more common way would be:
dateadd(hour, -1, getdate())
In your query, you do not need to cast to a string at all:
Select distinct m_record_server
from search_recording_file1
where tr_date_recorded >= getdate() - 1.0/24 and m_record_server is not null;
If you want the date that was there one hour ago (which seems to be the intent of the code, if not the rest of the question):
Select distinct m_record_server
from search_recording_file1
where tr_date_recorded >= cast(getdate() - 1.0/24 as date) and m_record_server is not null;

how to date format 103 to group by using where clause with string format (varchar(103),...,10)

Im having trouble on a query with a datetime field.
Its because i convert the datetime field to -varchar(10),..,103- so i can apply a where clause with date field on 103 format instead of datetime but then when i use the where clause it doesnt show results or group the way i need to, because the datetime field was converted to string.
Here is a simplified query for the example:
select ddate,SUM(ntotal) as Income from Inc_orders
where nbranch=2
and convert(varchar(10),ddate,103)
between '01/06/2010' and '31/06/2010'
group by convert(varchar(10),ddate,103)
order by ddfecha desc
ddate is the datetime field
ntotal is integer
nbranch is foreign key
Then what happens is that i get results from another 103 date range
01/10/2009 4447.0000
02/01/2010 26267.8000
02/02/2010 20498.0000
02/04/2010 22565.1000
02/05/2010 20539.0000
02/11/2010 33934.3000
02/12/2009 33587.4000
What i pretend to look it like is :
01/06/2010 29327.7000
02/06/2010 31170.4000
03/06/2010 37737.7000
04/06/2010 25109.6000
06/06/2010 20819.7000
10/06/2010 44703.9000
14/06/2010 21755.1000
15/06/2010 39369.3000
05/06/2010 29552.2000
07/06/2010 35305.9000
08/06/2010 30628.6000
..........
31/06/2010 18677.6000
A solution is not using datepart, month, or year functions because i need the
parameter to look like a calendar to apply a datetimepicker calentad combo object on it.
Do not use CONVERT(VARCHAR, DateField, 103) to remove the time from DATETIME it is inefficient and also causes problems when sorting.
Depending on the version of SQL-Server you are using there are 2 options that are usually regarded as the best. For SQL-Server 2008 and upwards use CAST(DateField AS DATE), for previous versions use DATEADD(DAY, 0, DATEDIFF(DAY, 0, DateField))
Because you are converting Ddate to a VARCHAR in this line:
convert(varchar(10),ddate,103) between '01/06/2010' and '31/06/2010'
you are removing the implicit conversion of '01/06/2010' and '31/06/2010' to dates. This means '02/01/2000' is greater than '01/01/2012' because you are comparing strings not dates. If you remove the time from Ddate and keep the expression in a date(time) format, '01/06/2010' and '31/06/2010' are implicitly converted to dates.
To illustrate this simply you can run this simple query:
SELECT CASE WHEN '02/06/2000' BETWEEN '01/06/2012' AND '03/06/2012' THEN 1 ELSE 0 END [String Comparison],
CASE WHEN CONVERT(DATETIME, '02/06/2000') BETWEEN '01/06/2012' AND '03/06/2012' THEN 1 ELSE 0 END [Date Comparison]
So your query would end up something like this:
SET DATEFORMAT DMY
SELECT CAST(DDate AS DATE) Ddate,
SUM(ntotal) as Income
FROM Inc_orders
WHERE nbranch=2
AND CAST(DDate AS DATE) BETWEEN '01/06/2010' AND '31/06/2010'
GROUP BY CAST(DDate AS DATE)
ORDER BY DDate
Or
SELECT DATEADD(DAY, 0, DATEDIFF(DAY, 0, DDate)) Ddate,
SUM(ntotal) as Income
FROM Inc_orders
WHERE nbranch=2
AND DATEADD(DAY, 0, DATEDIFF(DAY, 0, DDate)) BETWEEN '01/06/2010' AND '31/06/2010'
GROUP BY DATEADD(DAY, 0, DATEDIFF(DAY, 0, DDate))
ORDER BY DDate
ADDENDUM
I am not sure if Ddate contains a time, so using the above to remove the time may not be relevant, however the part about comparing strings in the where clause remains relevant. In addition there are very few occassions when it should be necessary to present your date to your application in string format. It would be better to keep the date as a date and format it within you application layer (whatever this may be).
Don't convert the date to a string, just leave it as a date:
select ddate,SUM(ntotal) as Income from Inc_orders
where nbranch=2
and ddate between '2010-06-01' and '2010-06-31'
group by nbranch
order by ddate
You can convert ddate in the select list, if you want it to display in a particular way.
You may convert document Date by :
ISNULL(CONVERT(varchar(12),tranInwardHeader.DocumentDate,103),'') AS DocumentDate
Do not use CONVERT nor in GROUP BY, nor in WHERE. use convert on SELECT list of fields
UPDATE:
See valid and recommended formats for DATE CONSTANTS at Microsoft. Please select a any format with "DATEFORMAT dependent: NO" and "Multilanguage: YES" in order to NOT have any problems in any language/setup
UPDATE:
i was writing just the same query #Blorgbeard when I saw: it wont work, because you cant group only by nbranch and have ddate on select list, also nbranch on group by has no sense because, only valid value is 2. You need to redefine your query/needs
I guess, your query may be:
select ddate,SUM(ntotal) as Income from Inc_orders
where nbranch=2
and ddate between '20100601' and '20100631'
group by ddate
order by ddate