Converting SQL Server null date/time fields - sql

Whenever the value is null for this query
SELECT ISNULL(someDateTime,'')
FROM someTable
the result is
someDateTime
------------
1900-01-01 00:00:00.000
I want it to be "No", so if I run this:
SELECT ISNULL(someDateTime,'No')
FROM someTable
then there's this error:
Conversion failed when converting datetime from character string.
How to do it? Thanks in advance!

The result of the expression will need to be a single type. If you want a character string (and you do, since 'No' is not a DateTime), you'll need to convert the datetime to such a string:
SELECT ISNULL(cast(someDatetime as varchar(20)), 'No') FROM someTable
As others have suggested, though, code like this smells bad, and you may want to pass the null to a client component and do the conversion there.

isnull() is trying to convert the second argument to the datatype of the field you specify in the first argument.
If you are going to be returning a string you need to cast the DateTime field to a string type so that isnull() can work properly - see Michael Petrotta's answer for a way to accomplish this.

You're still selecting a DateTime column, and so the result of that expression still needs to be a DateTime value rather than a string. To suggest an appropriate work-around, we'll need to know more about what you're really trying to do with this data.

You can't as such directly. It's easier to trap NULL in the client and change it to "no" there.
However, you could use a token value such as "17530101" which is a valid datetime, or CONVERT SomeDateTime first to varchar.
Otherwise, we need more info on why etc

In your Update Stored Proc: Update your previous date value to a new Null value:
.Parameters.AddWithValue("#Date_Value", Nothing).IsNullable = True

Related

SQL Error : Conversion failed when converting date and/or time from character string

I'm trying to convert a varchar column to date or datetime but I don't understand why it's not possible it should work and I don't see any kind of error.
The column values is 31-07-2017 and the type is Varchar(250). I tried convert and cast and I get the same error:
Conversion failed when converting date and/or time from character string.
Does anyone have any idea on why it's like this?
The conversion error is because your session setting is other than DATEFORMAT dmy or varchar values do not conform to DMY format.
For the latter case, run the query below to identify problem values:
SELECT YourDateColumn AS InvalidDate
FROM dbo.YourTable
WHERE
YourDateColumn IS NOT NULL
AND TRY_CONVERT(date, YourDateColumn, 103) IS NULL;
As #TimBiegeleisen mentioned in a comment, it is best to choose the most appropriate column type (date in this case) for the data to be stored. Not only will this avoid errors like this, it will improve performance and better ensure data integrity.
I found the issue, it's a very very stupid mistake, there was one column with a text format I couldn't see it because I checked with length, but the SQL gives max length so I used group by and manually check dates until I found one column that's not correct in 1 m account records

Select a date in a string and convert it to datetime

I have a string like:
'SPY US 03/20/20 P45'
I want to select just the date from the string.
My current query is:
Select Ticker, SUBSTRING(Ticker, PATINDEX('%[0-9][0-9]/[0-9][0-9]/[0-9][0-9]%',o.Ticker),8) AS 'myDate' FROM TABLE
This returns: 'SPY US 03/20/20 P45', 03/20/20
I want myDate to be in datetime.
I have tried various morphs of cast and convert, but they fail, presumably because they want the format to be in YYYY-MM-DD rather than MM/DD/YY.
My "smartest" attempt to convert was this:
CONVERT(DATETIME, SUBSTRING(o.Ticker, PATINDEX('%[0-9][0-9]/[0-9][0-9]/[0-9][0-9]%',o.Ticker),8),1)
After reading style guidelines here: https://www.w3schools.com/sql/func_sqlserver_convert.asp
but it still failed.
The ideal end-format for the date would be YYYY-MM-DD
Edited to add:
I have been fiddling with it and realized that I over simplied my question. The convert works if I just test it on a string, but the entire query involves several joins.
As I can understand you are looking for something like this.
You can use string_split() function to split string with blank space and then use try_cast() function to check each value whether it is a date.
declare #string as varchar(120) = 'SPY US 03/20/20 P4'
; with cte as (select
value
from string_split (#string, ' ')
)Select value from cte where try_cast (value as datetime) is not null
Live db<>fiddle demo.
So it turns out that there were a few entries in the column that didn't have friendly date format, so the patindex clause was returning nonsense.
For some reason that caused the entire operation to fail(rather than just returning null on the few entries that were failing).
Once I selected the entire (ultimately more complicated join statement) into a temp table, then I was able to try_convert the substring into a date and run my operations.

SQL Server ISDATE() Error

I have a table and need to verify that a certain column contains only dates. I'm trying to count the number of records that are not follow a date format. If I check a field that I did not define as type "date" then the query works. However, when I check a field that I defined as a date it does not.
Query:
SELECT
count(case when ISDATE(Date_Field) = 0 then 1 end) as 'Date_Error'
FROM [table]
Column definition:
Date_Field(date, null)
Sample data: '2010-06-27'
Error Message:
Argument data type date is invalid for argument 1 of isdate function.
Any insight as to why this query is not working for fields I defined as dates?
Thanks!
If you defined the column with the Date type, it IS a Date. Period. This check is completely unnecessary.
What you may want to do is look for NULL values in the column:
SELECT SUM(case when Date_Field IS NULL THEN 1 ELSE 0 end) as 'Date_Error' FROM [table]
I also sense an additional misunderstanding about how Date fields, including DateTime and DateTime2, work in Sql Server. The values in these fields are not stored as a string in any format at all. They are stored in a binary/numeric format, and only shown as a string as a convenience in your query tool. And that's a good thing. If you want the date in a particular format, use the CONVERT() function in your query, or even better, let your client application handle the formatting.
ISDATE() only evaluates against a STRING-like parameter (varchar, nvarachar, char,...)
To be sure, ISDATE()'s parameter should come wrapped in a cast() function.
i.e.
Select isdate(cast(parameter as nvarchar))
should return either 1 or 0, even if it's a MULL value.
Hope this helps.
IsDate takes a character string or exression that yeilds a character string as it's argument
The problem is this method ISDATE() only admits arguments of type datetime and smalldatetime within the "time" types, so it won´t work if you are using date type.
Also if you use date as type for that field, you won´t have to check the information there because it won´t admit other type of field.
You shoul only check for null values in your column, that´s all.

Like operator in Datetime column

I want to use Like operator in a column of datetime. The values of the column is as follows:
2013-08-31 17:54:52.000
2013-08-31 17:54:52.000
My query is as below:
SELECT * FROM table where created_date Like '%54%'
It works fine. but when I search for '%52%' instead of '%54%', it gives me nothing. (It is working when I search till the minutes, but when I search for seconds or milli seconds it does not work.)
I have looked at the following url and it is working
SQL LIKE Statement on a DateTime Type
I want to know the reason, why this is happening and how like operator works with datetime type column.
I think it would be a better idea to use the DATEPART operator of SQL SERVER to extract the portion of date.
And example could be like:-
SELECT * FROM table
where DATEPART(minute,created_date)=54
EDIT:-
I want to know the reason, why this is happening and how like operator
works with datetime type column.
Actually there is no direct support given by SQL Server for LIKE operator for DATETIME variable but you can always cast the DATETIME to a VARCHAR and then try to use the LIKE operator as you want.
On a side note:-
MSDN says:-
DATEPART can be used in the select list, WHERE, HAVING, GROUP BY and
ORDER BY clauses.
In SQL Server 2012, DATEPART implicitly casts string literals as a
datetime2 type. This means that DATEPART does not support the format
YDM when the date is passed as a string. You must explicitly cast the
string to a datetime or smalldatetime type to use the YDM format.
The 'LIKE' operator and any regular expression operators provided by other databases are used to process text values. A date is definitely not a text value, it is a separata type by itself.
It makes little sense to apply a text operator to a non-text type (like int or DATETIME or DATETIMEOFFSET), which is why you can't use LIKE on dates in any database. First of all, the values are not stored as text but in an implementation-specific binary form.
Then, while you can use LIKE on a specific text representation of a date, eg using CAST you have to absolutely certain what that representation is. Different locales display dates differently, with year first, year last, month first or last or whatever. What would you search against?
Moreover, what is 54? 54 minutes, 54 seconds or 654 milliseconds?
The only sensible solution is to use DATEPART to check specific parts of a date, or the BETWEEN operator to check for ranges.

TSQL derived column with date convert that checks for non-date convertible strings

I have a date column with dates stored as strings, such as 20120817. Unfortunately, the text form field that populates this column is free text, so I cannot guarantee that an occasional "E" or "whatever" shows up in this column. And more than a few already have.
What I need to do is convert the string column into a date column. Of course the convert will reject the random string characters. Is there any way to create a derived column that will not only convert the strings but exclude the non-date convertible strings?
If there were no non-date convertible strings in the table, the following would work:
ADD [convertedDate] AS CONVERT(DATE, [stringDate], 102)
And it does work perfectly in a test table I created. But when I introduce other non-convertible strings, I receive the dreaded "Conversion failed when converting date and/or time from character string" error for obvious reasons.
Is there a function that will catch non-convertible elements that I can add on to this derived column code? Or is a view or function the only - or best - way to handle this? I played around with IsDate() with little luck.
Thank you!
There's a function called ISDATE(date), maybe you can use it in a CASE statement or in the WHERE part of the query... It depends on how you're doing it, maybe something like this
ADD [convertedDate] AS CASE WHEN ISDATE([stringDate]) = 1 THEN CONVERT(DATE,[stringDate], 102) ELSE NULL END
If you're using SQL Server 2012 you can make use of the try_convert function
http://msdn.microsoft.com/en-us/library/hh230993.aspx
It will work normally if the conversion succeeds but return null if the conversion fails
ADD [convertedDate] AS TRY_CONVERT(DATE, [stringDate], 102)
This should give you some ideas...
DECLARE #date1 varchar(50)
DECLARE #date2 varchar(50)
SET #date1 = '20120101'
SET #date2 = 'e20120101'
SELECT
ISDATE(#date1),
ISDATE(#date2),
CASE WHEN ISDATE(#date1) = 1 THEN CONVERT(SMALLDATETIME,#date1) END,
CASE WHEN ISDATE(#date2) = 1 THEN CONVERT(SMALLDATETIME,#date2) END