0

These are my tables and sample records:

DEPARTMENT.Dept_nbr  (VARCHAR)
---------------------
(NULL)
UNK
00309
309

FPLAN.Department (NUMBER)
---------------------
D0309

Scenario:

I want FPLAN.Department (D0309) to be the reference and will display DEPARTMENT.Dept_nbr values.

My code:

select 
TRIM(REPLACE(FPL.DEPARTMENT, 'D')) as DEPARTMENT , DEPT.*
from
FPLAN FPL ,
(
select distinct(TRIM(LEADING 0 FROM DEPT_NBR)) DEPT_NBR from DEPARTMENT
) DEPT
WHERE
TRIM(LEADING 0 FROM FPL.DEPARTMENT) = DEPT.DEPT_NBR;

This brings NO RESULT.

What do I need to do to get this DEPT_NBR:

00309
309
boombox2014
  • 65
  • 2
  • 8
  • By what logic should 00309 and 309 match D0309? –  Nov 25 '16 at 22:42
  • this is resolved already. thank you for your time. – boombox2014 Nov 25 '16 at 23:28
  • 2
    this is not your private service site. It is hoped every question and answer will help others in the future. You got free advice, which helped you. The least you can do to "pay it forward" is to clarify what the problem was, so others would know if the answer could apply to their problem as well. Too bad this is too much of a demand on your time. –  Nov 26 '16 at 01:11

3 Answers3

2

Comment on nested queries and order of execution

The inner query is not guaranteed to be executed before the outer query and therefore does not protect you from bad conversions attempts.


create table t (x varchar2(10)); 

insert into t(x) values ('X123'); 

select  * 
from    (select x from t where regexp_instr(x,'([^0-9])') = 0) 
where   to_number (x) > 3
;

[Code: 1722, SQL State: 42000] ORA-01722: invalid number

Protected code -

select  * 
from    t
where   to_number(case regexp_instr(x,'([^0-9])') when 0 then x end) > 3
;
Community
  • 1
  • 1
David דודו Markovitz
  • 42,900
  • 6
  • 64
  • 88
0

If your meaningful strings are always in the format 'DXXXX' where XXXX represents a number, you may convert everything to numbers and then compare numeric values:

select Dept_nbr
from (
     select *
     from DEPARTMENT
     where regexp_instr( Dept_nbr,'([^0-9])') = 0
     ) 
       inner join FPLAN
         on ( to_number(trim( 'D' from Department)) = to_number(Dept_nbr) )
Aleksej
  • 22,443
  • 5
  • 33
  • 38
-1

SQL Server

If the field is already a string, this will work

SELECT RIGHT('000'+ISNULL(field,''),3) If you want nulls to show as '000'

It might be an integer -- then you would want

SELECT RIGHT('000'+CAST(field AS VARCHAR(3)),3) copied from here

Community
  • 1
  • 1