SQL Server Query Date convert Issue - sql

I want to add where condition in my query like 2012-10-05 00:29:06.338 <= Today'sdatetime however I am getting the issue.
Please help me to sort out this issue.
My query is given below :
Select * from table1
where
CONVERT(varchar(12),'2012-10-05 00:29:06.338', 106) + ' ' + CONVERT(varchar(12),'2012-10-05 00:29:06.338', 108) <= CONVERT(varchar(12), GETDATE(),106) + ' 23:59:00.000'

You can't do date comparisons by converting both values to a varchar. You need to convert the values to datetime and compare.
If you have a column in your database named col1 that is a datetime, you can compare this directly to GETDATE().
For example:
select * from table1 where col1 > GETDATE()
If you really need to compare a date with a string you can explicitly convert to datetime:
Select *
from table1
where CONVERT(DATETIME,'2012-10-05 00:29:06.338') <= GETDATE()
OR you can let SQL Server implicitly do the conversion for you:
Select *
from table1
where '2012-10-05 00:29:06.338' <= GETDATE()

You're trying to evaluate a string as a date:
Select '8'
where
CONVERT(DATETIME,CONVERT(varchar,Col1, 101))
+ ' ' + CONVERT(DATETIME,CONVERT(varchar,Col1,108))
<= CONVERT(DATETIME,CONVERT(varchar, GETDATE(),101))+' ' + CONVERT(DATETIME,CONVERT(varchar,'23:59:00.000', 108))

Related

Change date format dd/mm/yyyy to yyyy-mm-dd

am working in SQL Server 2008, while merging I got error like
conversion failed when converting datetime from character string
select *
from table_name
where cast(f_datetime as date) <=
cast(cast(datepart(year,cast(convert(varchar(250),#Year,103) as date) )as varchar(250))+ '-'+ cast(datepart(MM,cast(convert(varchar(10),#month,103) as varchar(50))+'-01' as date)
I cannot speak to the cast() on f_datetime. But for the rest, you can do:
where cast(f_datetime as date) <= convert(date, convert(varchar(250), #year * 10000 + #month * 100 + 1))
This simplifies the calculation, and prevents things like #year from being treated as a date due to the convert() function.
I assume your f_datetime field format is "dd/mm/yyyy". If yes you can easily convert this field instead of trying to merge and convert #year and #month fields. check this query :
SELECT *
FROM table_name
WHERE CONVERT(DATE,f_datetime,103)<= CAST(CONVERT(VARCHAR, #year) + '-' + CONVERT(VARCHAR, #month) + '-' + '01' AS DATE)

How to sql server difference query datetime varchar

I have variable time, format is varchar(8) in SQL Server
how result like this ?
I try with datediff.. but I can not do it.. because variable is type varchar...
sql server 2008 r2
Before using Datediff use Convert function to convert the varchar data into date
select datediff(dd,convert(date,date2),convert(date,date1))
From Yourtable
If you have any bad data which cannot be converted to date then who may have to filter out those data before converting to date.
If you are using Sql Server 2012+ then use TRY_CONVERT
select datediff(dd,try_convert(date,date2),try_convert(date,date1))
From Yourtable
Sqlfiddle Demo
Convert the varchar date into a proper date:
select datediff(day, cast(date1 as date), cast(date2 as date)) from your_table
Select
Datediff(day,
cast(left('20150201', 4) + '-' +
substring('20150201', 5, 2) + '-' +
right('20150201', 2) as DateTime),
cast(left('20150220', 4) + '-' +
substring('20150220', 5, 2) + '-' +
right('20150220', 2) as DateTime))
Try this to convert varchar into datetime

How to standardise a column of mixed date formats in T-SQL

Got a table in SQL Server which contains a varchar column with date data. Unfortunately the dates are in a whole slew of different formats.
2012-05-01
27/05/2012
07MAY2014
19/07/13
There may be others, but that's all I've encountered so far.
I need to squeeze these into a datetime column into another table, so I've been trying to select them as standard date-time values. At first, I thought that'd be easy:
UPDATE myTable
SET myDateColumn = CONVERT(DATETIME, myDateColumn, 103)
WHERE ISDATE(myDateColumn) = 0
But the trouble is that SQL Server treats dd/mm/yy and dd/mm/yyyy as separate formats. The former is code 3, and the latter is code 103. So whichever way I run that update, it chokes on the opposite format.
Is there any way I can select/update based on the date format, and get all these dates converted to a single valid DateTime format?
My guess is that you just have to try to differentiate between the different classes and handle each case in the appropriate way. Something like this:
declare #tab table (d varchar(20))
insert #tab values ('2012-05-01'),('27/05/2012'),('07MAY2014'),('19/07/13')
select
case
when isnumeric(left(d,4)) = 1 then cast(d as date)
when len(d) = 10 then convert(date, d, 103)
when len(d) = 8 then convert(date, d, 3)
when charindex('/',d) = 0 and isnumeric(d) = 0 then convert(date, d, 106)
end as [date]
from #tab
Output:
date
----------
2012-05-01
2012-05-27
2014-05-07
2013-07-19
It might not be that efficient, but I presume this is a one-off operation. I didn't write it as an update statement, but the query should be easy to adapt, and you should consider adding the converted date as a new proper datetime column if possible in my opinion.
Edit: here's the corresponding update statement:
update #tab
set d =
case
when isnumeric(left(d,4)) = 1 then cast(d as date)
when len(d) = 10 then convert(date, d, 103)
when len(d) = 8 then convert(date, d, 3)
when charindex('/',d) = 0 and isnumeric(d) = 0 then convert(date, d, 106)
end
from #tab
This is totally horrid, but it works with your example:
DECLARE #DodgyDates TABLE (
DateString VARCHAR(50));
INSERT INTO #DodgyDates VALUES ('2012-05-01');
INSERT INTO #DodgyDates VALUES ('27/05/2012');
INSERT INTO #DodgyDates VALUES ('07MAY2014');
INSERT INTO #DodgyDates VALUES ('19/07/13');
SELECT * FROM #DodgyDates;
--SELECT CONVERT(DATE, DateString) FROM #DodgyDates;--Fails
WITH DateDeconstruct AS (
SELECT
*,
CASE
WHEN DateString LIKE '____-__-__' THEN DateString
WHEN DateString LIKE '__/__/____' THEN RIGHT(DateString, 4) + '-' + SUBSTRING(DateString, 4, 2) + '-' + LEFT(DateString, 2)
WHEN DateString LIKE '__/__/__' THEN '20' + RIGHT(DateString, 2) + '-' + SUBSTRING(DateString, 4, 2) + '-' + LEFT(DateString, 2)
WHEN DateString LIKE '_________' THEN RIGHT(DateString, 4) + '-' + CONVERT(VARCHAR(2), DATEPART(MM, DateString)) + '-' + LEFT(DateString, 2)
END AS FixedString
FROM
#DodgyDates)
SELECT
DateString AS OriginalDate,
FixedString AS FixedDate,
CONVERT(DATE, FixedString) AS ConvertedDate
FROM
DateDeconstruct;
Results are:
OriginalDate FixedDate ConvertedDate
2012-05-01 2012-05-01 2012-05-01
27/05/2012 2012-05-27 2012-05-27
07MAY2014 2014-5-07 2014-05-07
19/07/13 2013-07-19 2013-07-19
In SQL Server 2012, you could use try_convert(). Otherwise, you could multiple updates:
UPDATE myTable
SET myDateColumn = CONVERT(DATETIME, myDateColumn, 103)
WHERE ISDATE(myDateColumn) = 0 AND MyDateColumn like '[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9]';
UPDATE myTable
SET myDateColumn = CONVERT(DATETIME, myDateColumn, 3)
WHERE ISDATE(myDateColumn) = 0 AND MyDateColumn like '[0-9][0-9]/[0-9][0-9]/[0-9][0-9]';
Note: the where clause will probably work here for the update. It does not work for a select. You may need to use a case as well:
UPDATE myTable
SET myDateColumn = (CASE WHEN ISDATE(myDateColumn) = 0 AND MyDateColumn like '[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9]'
THEN CONVERT(DATETIME, myDateColumn, 103)
ELSE myDateColumn
END)
WHERE ISDATE(myDateColumn) = 0 AND MyDateColumn like '[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-0]'
Also, you are putting the values back in the same column so you are overwriting the original data -- and you have another implicit conversion back to a string I would strongly recommend that you add another column to the table with a datetime data type and put the correctly-typed value there.
For this first you can convert all the data into another format such as 110 the USA date fromat, and then further again update the whole table with the desired format.

Combine two DateTimes

In SQL I have the following code fragment :
DECLARE
#DayPart as datetime,
#TimePart as datetime
SET #DayPart='2012-01-10 00:00:00.000'
SET #TimePart='2012-08-30 15:41:10.403'
Now I Need :
'2012-01-10 15:41:10.403'
How can I get it?
SELECT CONVERT(VARCHAR(10),#DayPart,111) + ' ' +
CONVERT(VARCHAR(10),#TimePart,108);
You should get #DayPart in 'yyyy-mm-dd' format and #TimePart in 'HH:MI:SS:MMM(24H)' format and concatenate two strings.
Try this
SELECT
CONVERT(char(10), #DayPart,126) + ' ' +
CONVERT(VARCHAR(12), #TimePart, 114)
More on SQL Server date formatting
SQL Server Date Formats
SQL2K8;
select #DayPart + cast(#TimePart as time)
SELECT REPLACE(CONVERT(VARCHAR(10),#DayPart,102),'.','-') + ' ' +
CONVERT(VARCHAR(10),#TimePart,108);
Other Date Formatting
But if you are using SQL Server 2008+
SELECT CONVERT(date, #DayPart) + ' ' + CONVERT(time, #TimePart)

converting date from varchar to date

I am trying to change the date format of a column, the column is set as varchar column name date time. The problem is that i cannot actually change the data type because the data is automatically inputted by a PLC on the automation side. I need the date in a date or numeric value because when i run my queries i need to give the system a date range. I am trying to use substrings to work around this issue but am getting an error saying that the data type is out of range. here is the syntax of my query.
select cast(
(substring(datetime, 1, 4) + '-' +
SUBSTRING(DateTime, 5, 2) + '-' +
SUBSTRING(DateTime, 7, 2) + ' ' + '00:00:00.000') as dateTime) as "Date"
, ID1
, ID2
, diameter
, WeightTheoretical
, WeightActual
, StockType
from table1
where datetime is not null
and datetime <> ''
and datetime <> '0'
order by "Date", ID1;
Edit- the date format is as such 20120622:00:00:00:000
Assuming your date is with the format yyyymmdd, you can convert the varchar to datetime like this:
select convert(datetime, columname, 112)
It looks from your SQL that your date string is of the format YYYYMMDD
This should convert fine using either the CAST or CONVERT functions:
eg
SELECT CONVERT(datetime,'20120601')
SELECT CAST('20120601' as datetime)
both return the expected value as a datetime.
EDIT: Based on the supplied format you specified, I'd use the SubString to chop the supplied data down a bit:
eg
SELECT CONVERT(datetime,SUBSTRING('20120601',1,8))
Based on the format of your data in the table (20120622:00:00:00:000) you can do the following:
declare #date varchar(50)
set #date = '20120622:00:00:00:000'
select cast(left(#date, 8) as datetime)
or
select convert(datetime, left(#date, 8))
results:
2012-06-22 00:00:00.000