Cast VARCHAR as INT keeping NULLs and setting text value to number

ttist25 used Ask the Experts™
Good morning,

I'm creating an int field from a varchar field in a staging table in SQL Server 2012.  

The field contains NULL values, positive and negative integers, and the text value "Unknown".

I would like to create a new int field and update it with the numeric values, set the text value of "Unknown" to 88888 and keep the NULL values as NULL.

I "tried" TRY_CAST but I really need the text "Unknown" set to the 88888 value because in this instance "Unknown" has a different meaning than NULL.  

Any help will be greatly appreciated.

Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Senior Developer
If your description is precise, then you just missed the next step: Just a IIF().

IIF(yourTextColumn = 'Unknown', '88888', TRY_CAST(yourTextColumn AS INT))

Open in new window


Awesome!  THanks ste5an!
Ryan ChongSoftware Team Lead


     when yourTextColumn  is null then null
     when yourTextColumn  = 'Unknown' then 88888
     else cast(yourTextColumn as int)

Open in new window

then values of yourTextColumn only contain Unknown, Nulll or integer values in varchar.

you need to tell us if there is exceptional cases, whereas the varchar values not equal to "Unknown"

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial