Reputation: 847
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 -
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?
Upvotes: 1
Views: 62
Reputation: 2770
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.
Upvotes: 2
Reputation: 2210
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;
Upvotes: 0
Reputation: 1270883
Don't use replace()
. Use case
:
(case when locationNbr = '0' then '1035' else locationNbr end)
Upvotes: 1