We help IT Professionals succeed at work.

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

85 Views
Last Modified: 2018-12-20
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!
Comment
Watch Question

Senior Developer
CERTIFIED EXPERT
Commented:
This problem has been solved!
(Unlock this solution with a 7-day Free Trial)
UNLOCK SOLUTION

Author

Commented:
Awesome!  THanks ste5an!
CERTIFIED EXPERT

Commented:
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"

Gain unlimited access to on-demand training courses with an Experts Exchange subscription.

Get Access
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Empower Your Career
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions