简体   繁体   中英

sql query for masking only 1st 5 char of value

i need your help in creating the below query for "I have a column called 'A' with 10 digits in length I also have a column called 'B'

   A                                   B
1234567890                           SAM
2345678912                           HELLO
7364557382                           MORNING 

I want to mask column A and replace the first 5 digits with column B.

Post masking :

SAM   67890  (with 2 spaces)
HELLO78912 
MORNI557382   

You can use string functions:

select t.*, rpad(b, 5, ' ') || substr(a, 6) res
from mytable t

If a is a number, you can explictly cast it first:

select t.*, rpad(b, 5, ' ') || substr(to_char(a), 6) res
from mytable t

You can use RPAD( B, 5, ' ' ) || SUBSTR( A, -5 ) RPAD( B, 5, ' ' ) || SUBSTR( A, -5 ) to get the first 5 characters of B (right-padded with spaces if required) concatenated with the last 5 characters of A .

For example:

SELECT A,
       B,
       RPAD( B, 5, ' ' ) || SUBSTR( A, -5 ) AS masked_value
FROM   table_name

With the sample data:

CREATE TABLE table_name ( A, B ) AS
SELECT 1234567890, 'SAM'     FROM DUAL UNION ALL
SELECT 2345678912, 'HELLO'   FROM DUAL UNION ALL
SELECT 7364557382, 'MORNING' FROM DUAL

Outputs:

\n         A | B | MASKED_VALUE \n---------: |  :------ |  :----------- \n1234567890 |  SAM | SAM 67890  \n2345678912 |  HELLO | HELLO78912  \n7364557382 |  MORNING | MORNI57382   \n

db<>fiddle here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM