Using ISNULL or COALESCE on date column - sql

I’ve got a date column where some rows have got NULL values. I would like to use ISNULL or something like that to substitute those values with something like ‘N/A’, however, when I try to use ISNULL, I get an error due to two different data types. If I try to convert my Date column to VARCHAR in order to be able to use ISNULL, then the way my column displays dates gets distorted. Is there any way to solve this problem?
ISNULL(DateSent, 'N/A')

I recommend COALESCE(), because it is standard. However, your problem is that the first column is a date/time and that is not compatible with a string.
So, you need to convert the value. You can use the default format:
COALESCE(CONVERT(VARCHAR(255), DateSent), 'N/A')
Or you can add a conversion argument:
COALESCE(CONVERT(VARCHAR(255), DateSent, 120), 'N/A')
Or you can use FORMAT() for more flexibility.

You can try this
Select ISNULL(Cast(DateSent as Varchar(20)), 'N/A')
Below is one example:
declare #DateSent date = getdate()
Select ISNULL(Cast(#DateSent as Varchar(20)), 'N/A')
For null values as below.
declare #DateSent1 date = NULL
Select ISNULL(Cast(#DateSent1 as Varchar(20)), 'N/A')

Related

Conversion from INT to varchar in sql

I have a table where there are values like 20170730 and also 0 values are there which is INT type
I am trying to convert it to value like 30/07/2017, for which i am using the below code,
Select convert(NVARCHAR(10),convert(date,convert(NCHAR(8),datecolumn)),103) from table
But for the zero values i am getting the below error
Conversion failed when converting date and/or time from character string.
If i delete all the zero this working fine but problem having with zero.
My requirement is to convert when there a date value and if 0 are there then it should be zero only like below,
Result
30/07/2017
0
Can u pls help
As already pointed out in the comments, you can try to use a CASE expression
SELECT CASE
WHEN nmuloc = 0 THEN
'0'
ELSE
convert(varchar(10),
convert(date,
convert(varchar(8),
nmuloc),
112),
103)
END
FROM elbat;
or try_convert() and coalesce().
SELECT coalesce(convert(varchar(10),
try_convert(date,
convert(varchar(8),
nmuloc),
112),
103),
'0')
FROM elbat;
db<>fiddle
The latter one will also correct other "malformed" data like 123 for example. The former will also fail in such cases. You may want that or not.
But, as also already pointed out in the comments, your real problem is that you use an inappropriate data type. Change the column's datatype to some date/time data type to really fix this.

Convert from varchar(50) to date

I have imported csv file to sql server manager. one of column is date but his data type is vachar(50).
I used the basic (cast, convert, try_parse) but still get message:
(Conversion failed when converting date and/or time from character
string.)
could you please help me :)
select cast(
replace(
case
when [factuur_datum] in ('null','')
then null
else [factuur_datum]
end, '-','') as date) as [factuur_datum]
from [dbo].[verkoop]
Please use below query to convert it into date
convert(date,'20-12-2018',105)
This should do what you intend:
select try_cast(replace(factuur_datum, '-', '') as date) as factuur_datum
from [dbo].[verkoop]
Non-dates will result in NULL.
I take it factuur_datum is the date column:
select
cast(factuur_datum as date) as [Alias]
from [dbo].[verkoop]
Not sure what the data looks like so can you include an example?
EDIT
convert(datetime,'factuur_datum',1)
possibly will error out if there are null values so you may need to case out the nulls then convert.

Convert VARCHAR to DATE in SQL SERVER

I have VARCHAR column (MyValue) in my table. It has date value in two different format.
MyValue
----------
25-10-2016
2016-10-13
I would like to show them in DATE format.
I wrote query like below:
SELECT CONVERT(date, MyValue, 105) FROM MyTable
SELECT CAST(MyValue as date) FROM MyTable
Both are giving me this error. Conversion failed when converting date and/or time from character string.
Is there anyway convert to DATE datatype format even the value stored in different formats like above?
Expecting your answers. Thanks in advance.
Does this help?
declare #varchardates table
(
vcdate varchar(20)
)
INSERT INTO #varchardates VALUES
('25-10-2016'),
('2016-10-13')
SELECT CONVERT(date,vcdate, case when SUBSTRING(vcdate, 3, 1) = '-'
THEN 105 ELSE 126 END) as mydate
FROM #varchardates
Depending on how many different formats you have in your data, you may need to extend the case statement!
See here for list of the different format numbers
You can use TRY_CONVERT and COALESCE. TRY_CONVERT returns NULL if the conversion fails, COALESCE returns the first NOT NULL value:
SELECT COALESCE(TRY_CONVERT(DATETIME, x, 105), TRY_CONVERT(DATETIME, x, 120))
FROM (VALUES('25-10-2016'), ('2016-10-13')) a(x)
I assumed the value 2016-10-13 is in format yyyy-MM-dd.
You mention in a comment you may have other formats as well. In that case it gets very tricky. If you get a value 01-12-2017 and you have no idea about the format, there is no way to tell whether this is a date in januari or in december.

SQL Server - How to use convert with ISNULL

Something like the example below:
SELECT SSN, Name, CONVERT(VARCHAR(50), Hours) ISNULL(Hours, '')
where I want to convert an int to varchar and at the same time set the null values as an empty string. How can I do to make this possible?
ISNULL(CONVERT(VARCHAR(50), Hours), '')
An alternative option if you are on 2012+ would be to use
SELECT CONCAT(Hours,'')
which has the same end result of converting to string and returning empty string instead of NULL.
Wrap your convert in the isnull;
SELECT
SSN
,Name
,ISNULL(CONVERT(VARCHAR(50), Hours), '')
This way it will allow for the nulls to be pulled on the conversion, you won't be able to do the isnull inside the convert as a zero length character won't be compatible with an int field (or other number only field).

SQL-Should I use nested Query to first correct erroneous data and then convert to datetime?

There is one column: OpenedDate with datatype: varchar(8) and I want to convert it into datetime but since OpenedDate has erroneous values of 0's.
First- I want to convert the 0's into NULLs using the query:
CASE WHEN Opened_dt = '0'
then 'NULL'
else Opened_dt
end as 'Opened_dt_converted'
Now, I want to use the above results to convert the datatype to DateTime using the syntax:
CONVERT(DATETIME, 'Opened_dt_converted',120)
I was thinking if I should use Nested query or create a stored procedure but I am not sure how can I use the nested query for this type of situation?
Basically, I want this whole query in one stored procedure. Could you please help me in achieving that task?
Thanks in advance!
Geetanjali
If you are using SQL Server 2012+, just use try_convert():
select try_convert(DateTime, OpenedDate, 120)
If it fails, then you'll get NULL. In older versions, you would just use a case:
select (case when OpenedDate like '[0-9][0-9][0-9]-[0-1][0-9]-[0-3][0-9]'
then convert(DateTime, OpenedDate, 120)
end)
Note: I just put in a format that would often work for date. The time component is similar.
Sub-select or CTE should work for you.
SELECT CONVERT(DATETIME, Opened_dt_converted, 120) AS dt_converted
FROM (SELECT CASE
WHEN Opened_dt = '0' THEN NULL
ELSE Opened_dt
END AS Opened_dt_converted
FROM yourtable) a
or use Case statement to skip the zero from convertion
SELECT CASE
WHEN Opened_dt = '0' THEN NULL
ELSE CONVERT(DATETIME, Opened_dt, 120)
END AS dt_converted
FROM yourtable