Conversion from INT to varchar in sql - 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.

Related

Handling a value of zero in a date datatype

I'm reporting out of a database that is using decimal(17,6) as the datatype for a date field. For example, the current date/time in this field would be 20210820.171900. Unusual, but whatever. I need to convert the original date field from decimal(17,6) to datetime. This is what I have:
SELECT convert(datetime, convert(varchar,convert(int, lastmoddatetime)), 0)
from Table1
The above statement works correctly as long as none of the records have a value of zero in this column. Unfortunately, the column value defaults to zero (0.000000) if no date has been calculated for it. Whenever a column has a zero value, I get the following error:
Conversion failed when converting date from character string.
How can I overcome this issue? Ultimately, I'm needing to apply a dateadd function to the lastmoddatetime field.
Note: Before you suggest changing the column definition, this database originated in the 1990's and I'm not allowed to make any changes to the database structure.
You can use NULLIF to null out those values
convert(datetime, convert(varchar(15), convert(int, NULLIF(lastmoddatetime, 0.0))), 0)
Either use TRY_CONVERT or CASE - depending how you want to handle the zero case.
SELECT
-- If desiring null for 0 and SQL Server 2012+
TRY_CONVERT(date, CONVERT(varchar, CONVERT(int, lastmoddatetime)), 0)
, CASE WHEN lastmoddatetime <> 0
-- If desiring some other valid date or < SQL Server 2012
THEN CONVERT(date, CONVERT(varchar, CONVERT(int, lastmoddatetime)), 0)
ELSE NULL /* Whatever valid datetime value you want */ END
FROM (
VALUES (20210820.171900), (0.0)
) x (lastmoddatetime);
I note that this ignores the time component - so am converting to a date not datetime above. If you need to handle the time component you need to update your question.
Yet another option.
You can thin it out a bit by using left() and try_convert()
Example
Declare #YourTable table (lastmoddatetime numeric(17,6))
Insert into #YourTable values
(20210820.171900)
,(0.0)
Select AsDate = try_convert(date,left(lastmoddatetime,8))
,AsDateTime = try_convert(datetime,left(lastmoddatetime,8))
From #YourTable
Results
AsDate AsDateTime
2021-08-20 2021-08-20 00:00:00.000
NULL NULL
use
convert(datetime,convert(int,lastmoddatetime),0)

SQL Server 2017 Convert Varchar to Date

I have a date stored as nvarchar which I cannot seem to convert to a date.
I have tried the following but get the error message
Conversion failed when converting date and/or time from character string
select cast([month-year] as date) from [Reporting].[AIM].[Hires_PBI]
select convert(date, [month-year], 103)from [Reporting].[AIM].[Hires_PBI]
Any ideas here?
Find the values that are causing the problem using try_convert():
select [month-year]
from [Reporting].[AIM].[Hires_PBI]
where try_convert(date, [month-year], 103) is null and
[month-year] is not null;
Once you see what values are causing the problem, you can adjust the conversion logic to convert all values. Or just use try_convert() to get NULL for the non-convertible values.

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.

Using ISNULL or COALESCE on date column

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')

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.