How to convert a column wit varchar(max) in int

366 views Asked by At

I have the following problem:

I have a table ArticleDescription with columns like this:

ID (int)            Description (varchar(max))
1                   Muller Bogen, chrome-14440416700-55
2                   Muller Bogen, chrome-14440416700-55
3                   Muller Geruchverschluss 1 1/4ยจ, black-11188870-00
                    Muller Ma.02 Waschtisch-Wand-Einhandbatterie ohne Ablaufgarnitur, white-12345678-08

I only want to convert the datatype of the column Description to int.

I have tried:

SELECT (case when isnumeric(Description) = 1 then cast(Description as int) end)
FROM   ArticleDescription

But I get the following message:

Meldung 245, Ebene 16, Status 1, Zeile 20 Fehler beim Konvertieren des varchar-Werts "Dornbracht Bogen-04240418900-00" in den int-Datentyp.

1

There are 1 answers

2
Brian Edwards On

Data columns must all be of the same type. In order to do this, you will need to have an acceptable alternative value for the remainder of the rows.

declare @foo table(
    ID int,
    Description varchar(20) null
)

insert into @foo
values(1,'one')
,(2,'2')
,(3,'')
,(4,null)

select 
ID,
CASE WHEN ISNUMERIC(Description) = 1 then CAST(Description as INT) ELSE null END as [Parsed Description]
from @foo

or you can add a where clause to only select numeric descriptions

select 
ID,
CAST(Description as INT)  as parsed_pescription
from @foo foo
where ISNUMERIC(Description) = 1