Error when using DateAdd - TSQL - sql-server-2008

I have an app that uses a table that has a varchar column [BadColumn] which is populated by a date in the format MM/DD/YYYY or at least that's what most of the rows contain.
I have no control on modifying this table and changing the data type.
I need to report on this data to show rows that are within a week.
Here's my problem:
every time I use something to compare/filter the date I get an error
Conversion failed when converting date and/or time from character string
So here's what I have tried so far :
Tried to create a view with the [BadColumn] being converted to a Date type column [NewBadColumn] and convert the value from the original table to a date type using Convert(date, BadColumn). The view gets populated, but now when I still try to query using DateADD or do any date comparisons I get the same error.
I have also tried to use Convert(Date, BadColumn, 105), but same problem.
I have tried other formats, but still the same issue cannot do a date comparison on that column.
I am not sure which row is throwing the error, how do I find it and fix this issue.
Thank you for the responses. I have tried using ISDate function to find the bad records.
But I am still getting the same error "Conversion failed when converting date and/or time from character string." when I try to use DateAdd.
Here's the code I am using :
Select t.*
from
(Select * from dbo.BadTableName q with (nolock)
where ISDate(BadColumn)=1 and ISDATE(BadColumn) Is Not Null
) t
where t.BadColumn > DATEADD(dd,-2, GetDATE())
Any help is appreciated.

Try checking the column using the ISDATE() function. You can do this without creating a view first.
IF ISDATE(YourColumn) = 1
DATEADD (datepart , number , YourColumn )
ELSE 'No valid date provided'

Look at this other stack over flow question and answer
Find invalid dates in SQL Server 2008
You can use the ISDATE function to test the individual rows.

Related

How can I convert a varchar into a date in MySQL Workbench?

Probably it's super simple but i've been stuck some hours on this.
I have a column called "Publish_Date" which is a varchar, but my date shows like this: 17.01.11 (year.day.month) and I want to convert it to a date (at this point, any date format it's ok).
Every time i tried to use "convert" or "cast" it gives me a syntax error or the data doesn't change or all the data in the column changes to "null" values.
I'd appreciate if you can help me.
Assuming your data is all greater than 2000 then you can add missing part of YEAR then cast it.
SELECT CAST(CONCAT('20', Publish_Date) AS DATETIME);
You can use STR_TO_DATE with the format %y.%m.%d since this is how your date value is stored
select
str_to_date(birth_date, '%y.%m.%d')
from
mytable
Here is an SQL Fiddle I created for this case

How to convert a string to date and extract values in Access query

I'm using Access DB 2007 - 2010; I've tried to import many CSV files but the timestamp column keeps failing to import correctly.
So I linked all of the CSV's to an Access DB and I'm trying to query all of the tables.
I'm trying to extract the year and day of the year from the time stamp (which is currently a string)
I'm trying to combine the Format with datepart functions and it keeps failing. (it just says error in the table)
The format function by itself works but I can't combine it with anything.
I'm basically trying to do this:
select datepart("y", Format(gmt, "dd-mmm-yyyy hh:nn:ss")) as DOY from Table1;
but it fails. I've also tried CDate and DateValue in different combinations but it all fails.
Does anyone know how to get this to work?
UPDATE
The format function isn't doing anything. The text remains the same no matter how I try to format it.
Here's a datetime sample: 05-Dec-2008 13:40:01.955
Access can't cope with the milliseconds in your date strings.
Use Left() to exclude them and feed the resulting substring to CDate().
SELECT CDate(Left(gmt, 20)) AS date_from_string
FROM Table1;
Once you have a valid Date/Time value, you can use Year(<Date/Time value>) or DatePart("yyyy", <Date/Time value>) to extract the year. And DatePart("y", <Date/Time value>) will give you the day of the year.
Just solve this issue, here is my code for your reference:
update tablename
set date=cdate(format(left(gmt,4)&"-"&right(gmt,2),"yyyy-mm"))

Calculating age in conditional split transformation

I've a requirement to split a table contents based on the age and I've a column DOB which is in string format and is of type '19910930'.I've used the following command and it works fine when run
DATEDIFF( YY,CONVERT(date,[DOB]),CONVERT(date, GETDATE()))
and the same gives an error when I try it as condition in Conditional Split transformation as
DATEDIFF( YY,CONVERT(date,[DOB]),CONVERT(date, GETDATE()))<=25
I even tried a Derived Column transformation with the same expression and that too ain't working.
Could you please help me as where I'm missing out in this?
--Vijay
try converting in this way:
DATEDIFF("YY",(DT_DATE)( SUBSTRING(#[User::DOB] ,1,4)+"-"+SUBSTRING (#[User::DOB] ,5,2)+"-"+SUBSTRING (#[User::DOB] ,7,2)) ,GETDATE())
DateDiff by year will not work when the day is between the first of the year and the [DOB]. As long as your [DOB] is in form YYYYMMDD. You can use this formula to get the age...
select
CurrentAge = ((convert(varchar(8), getdate(), 112) - cast([DOB] as int)) / 10000)
the same formula in an SSIS expression would be very clunky with a bunch of DatePart calls to format the current date [System::ContainerStartTime] into the YYYYMMDD form and a conversion of [DOB] into DT_I4. I'd advise to do the calulation in the SQL select if possible.
Thanks Jayvee and dotjoe...I couldn't get it done either way But I instead used your suggestion to calculate age as a new column in the SQL itself while generating Source and could get the required result using condition split.
DATEDIFF(YY,CONVERT(DATE,DOB),CONVERT(DATE,GETDATE())) as Age
I hope there should be a way this can be done in Derived Column though..
Vjai

UNIX_TIMESTAMP outputting NULL in MySQL?

I've got a table setup which has populated data. In column "date", I have dates in the following format:
yyyymmdd i.e. 20131110
I have created a new field and called it newdate with the text format.
Then, I open up the SQL window and put the following in
UPDATE wl_daily
SET
newdate = UNIX_TIMESTAMP(date)
For some reason, it is running correctly, however it only outputs NULL to all the rows. Also, the column name is blank for some reason
Any suggestions?
That's because your field in a string and you're trying to add timestamp to it which is not a string. You need to use a valid datetime field like timestamp for this to work.
Advice: don't store dates and times as strings. Store them in their native format. It makes working with dates and times much easier.
While John Cronde's answer is correct - it doesnt help your situtation
UNIX_TIMESTAMP(STR_TO_DATE(`date`, '%Y%m%d'))
will do the conversion for example
SELECT UNIX_TIMESTAMP(STR_TO_DATE('20131111', '%Y%m%d'))
returns
unix_timestamp(STR_TO_DATE('20131111', '%Y%m%d'))
---------------------------------------------------
1384128000
You should only use this to convert your columns to the date specific columns. Converting each time you need a number will add load and slow down the query if used in production

SQL Server 2008 VarChar To DateTime

I have a table where unfortunately a number of dates are stored as strings.
I have a number of reports that cast them to datetimes and filter by them. This was working fine until today when all of a sudden i'm getting this error
"The conversion of a varchar data type to a datetime data type resulted in an out-of-range value."
The dates are all stored in the format of "yyyy-mm-dd" and are all valid.
If I run the following SQL statement
SELECT CAST('2010-06-02' AS DateTime)
I would expect to get "2010-06-02" however as of today I'm getting "2010-02-06" something has changed with the way SQL formats dates. I've had a look in regional settings on the server and it all looks to be correct.
What else could be causing this?
Try setting the format explicitly
select convert(datetime, '2010-06-02',101)
An unambiguous way of getting this conversion is to do the following:
SELECT CAST(replace('2010-06-02', '-', '') AS DateTime)
And that will always be interpreted as YYYYMMDD, ignoring the set dateformat ydm declaration or any cultural settings that the database has.
Q1: What else could be causing this?
The local, You probably are under the local101(US) and put data from 103 (British/French)
Like barry sad use convert