1

I've got a query pulling data from a table. In one particular field, there are several cases where it is a zero, but I need the four digit location number. Here is where I'm running into a problem. I've got

SELECT REPLACE(locationNbr, '0', '1035') AS LOCATION...

Two issues -

  1. Whoever put the table together made all fields VARCHAR, hence the single quotes.
  2. In the cases where there already is the number 1035, I get 1103535 as the location number because it's replacing the zero in the middle of 1035.

How do I select the locationNbr field and leave it alone if it's anything other than zero (as a VARCHAR), but if it is zero, change it to 1035? Is there a way to somehow use TO_NUMBER within the REPLACE?

3 Answers 3

2
SELECT CASE WHEN locationNbr='0' THEN '1035' ELSE locationNbr END AS LOCATION...

REPLACE( string, string_to_replace , replacement_string )

REPLACE looks for a string_to_replace inside a string and replaces it with a replacent_string. That is why you get the undesired behaviour - you are using the wrong function.

CASE WHEN condition THEN result1 ELSE result2 END CASE checks a condition and if it is true it returns result1 and if it is not it will return result2. This is a simple example, you can write a case statement with more than one condition check.

Sign up to request clarification or add additional context in comments.

Comments

1

Don't use replace(). Use case:

(case when locationNbr = '0' then '1035' else locationNbr end)

Comments

0

You can make use of length in Oracle:

select case when length(loacation) = 1 then REPLACE(loacation, '0', '1035') else loacation end as location
from location_test;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.