Avatar of ttist25
ttist25
 asked on

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

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.

Thanks!
Microsoft SQL ServerSQL

Avatar of undefined
Last Comment
Ryan Chong

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
ste5an

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
ttist25

ASKER
Awesome!  THanks ste5an!
Ryan Chong

or

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

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"
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy