2016-08-11 4 views
0

문자열이 x-y+z입니다. x, y 및 z 값은 표에 저장됩니다. 라고 말합니다.문자열에서 값 대체/대체

x 10 
y 15 
z 20 

이 문자열은 10-15+20처럼 변경해야합니다.

어쨌든 나는 이것을 plsql 또는 sql을 사용하여 얻을 수 있습니까? 간단한 피벗을 사용하여

+0

방법 SQL의 기능을 대체 사용에 대한? 같은 뭔가 : 선택 교체 ('x + y를 - z', 'x', (여기서 varValue myTab에서 ID를 선택 '='x ') – Plirkee

답변

0

우리는이 같은 테이블 가정, 다음을

DECLARE @Table1 TABLE 
    (name varchar(1), amount int ) 
; 

INSERT INTO @Table1 
    (name , amount ) 
VALUES 
    ('x', 10), 
    ('y', 15), 
     ('Z', 25); 

스크립트

Select CAST([X] AS VARCHAR) +'-'+CAST([Y] AS VARCHAR)+'+'+CAST([Z] AS VARCHAR) from (
select * from @Table1)T 
PIVOT (MAX(amount) FOR name in ([X],[y],[z]))p 
+0

하지만 이런 종류의 요구 사항은 실제 시나리오에 존재하지 않습니다 당신이 연습 목적을 위해 생각 이 질문을 게시했습니다 – mohan111

+0

아니 연습 목적을 위해, 그 프로젝트 요구 사항, 이상한 하나 참으로 –

0

을위한 접근 방법이 될 수 있습니다 수행 할 수 있습니다

create table stringToNumbers(str varchar2(16), num number); 
insert into stringToNumbers values ('x', 10); 
insert into stringToNumbers values ('y', 20); 
insert into stringToNumbers values ('zz', 30); 
insert into stringToNumbers values ('w', 40); 

먼저 토큰 화를 당신의 다음과 같이 입력 된 문자열 :

SQL> with test as (select 'x+y-zz+w' as string from dual) 
    2 SELECT 'operand' as typ, level as lev, regexp_substr(string, '[+-]+', 1, level) as token 
    3 FROM test 
    4 CONNECT BY regexp_instr(string, '[a-z]+', 1, level+1) > 0 
    5 UNION ALL 
    6 SELECT 'value', level, regexp_substr(string, '[^+-]+', 1, level) as token 
    7 FROM test 
    8 CONNECT BY regexp_instr(string, '[+-]', 1, level - 1) > 0 
    9 order by lev asc, typ desc; 

TYP   LEV TOKEN 
------- ---------- -------------------------------- 
value   1 x 
operand   1 + 
value   2 y 
operand   2 - 
value   3 zz 
operand   3 + 
value   4 w 

예에서는 소문자 리터럴을 사용하고 +/- 기호 만 사용했습니다. 좀 더 복잡한 것을 처리하기 위해 쉽게 편집 할 수 있습니다. 또한 입력 문자열이 올바른 것으로 가정합니다.

는 그런 다음 연결을 구축, 토큰 화 된 문자열로 디코딩 테이블에 가입 할 수 있습니다 :

SQL> select listagg(nvl(to_char(num), token)) within group (order by lev asc, typ desc) 
    2 from (
    3   with test as (select 'x+y-zz+w' as string from dual) 
    4   SELECT 'operand' as typ, level as lev, regexp_substr(string, '[+-]+', 1, level) as token 
    5   FROM test 
    6   CONNECT BY regexp_instr(string, '[a-z]+', 1, level+1) > 0 
    7   UNION ALL 
    8   SELECT 'value', level, regexp_substr(string, '[^+-]+', 1, level) as token 
    9   FROM test 
10   CONNECT BY regexp_instr(string, '[+-]', 1, level - 1) > 0 
11   order by lev asc, typ desc 
12  ) tokens 
13  LEFT OUTER JOIN stringToNumbers on (str = token); 

LISTAGG(NVL(TO_CHAR(NUM),TOKEN))WITHINGROUP(ORDERBYLEVASC,TYPDESC) 
-------------------------------------------------------------------------------- 
10+20-30+40 

이 당신의 모든 문자 입력 문자열이 테이블에 corrensponding 값이 있다고 가정합니다.

SQL> select listagg(
    2     case 
    3     when typ = 'operand' then token 
    4     else to_char(nvl(num, 0)) 
    5     end 
    6    ) within group (order by lev asc, typ desc) 
    7 from (
    8   with test as (select 'x+y-zz+w-UNKNOWN' as string from dual) 
    9   SELECT 
..   ... 
16  ) tokens 
17  LEFT OUTER JOIN stringToNumbers on (str = token); 

LISTAGG(CASEWHENTYP='OPERAND'THENTOKENELSETO_CHAR(NVL(NUM,0))END)WITHINGROUP(ORD 
-------------------------------------------------------------------------------- 
10+20-30+40-0 
0

이 같은 함수 만들기 : 당신은 예를 들어 0을 할당, 아니 corrensponding 번호 문자열의 경우를 처리 할 수 ​​있습니다 여기에

create table ttt1 
    (name varchar(1), amount int ) 
; 

INSERT INTO ttt1 VALUES ('x', 10); 
INSERT INTO ttt1 VALUES ('y', 15); 
INSERT INTO ttt1 VALUES ('z', 25); 

CREATE OR REPLACE FUNCTION replace_vars (in_formula VARCHAR2) 
    RETURN VARCHAR2 
IS 
    f VARCHAR2 (2000) := UPPER (in_formula); 
BEGIN 
    FOR c1 IN ( SELECT UPPER (name) name, amount 
        FROM ttt1 
       ORDER BY name DESC) 
    LOOP 
     f := REPLACE (f, c1.name, c1.amount); 
    END LOOP; 
    return f; 
END; 

select replace_vars('x-y+z') from dual 
0

을 그것을 시도 문제에 접근하는 또 다른 방법 모두 SQL에. 반드시 가장 유연하거나 가장 빠른 것은 아니지만 어쩌면 문제에 접근하기 위해 다른 방법으로 아이디어를 얻을 수 있습니다. 또한 최종 공식을 실행하여 답을 얻는 방법을 보여줍니다. 아래의 설명을 참조하십시오.

모든 변수가 변수 테이블에 있다고 가정합니다.

-- First build the table that holds the values. You won't need to do 
-- this if you already have them in a table. 
with val_tbl(x, y, z) as (
    select '10', '15', '20' from dual 
), 
-- Table to hold the formula. 
formula_tbl(formula) as (
    select 'x-y+z' from dual 
), 
-- This table is built from a query that reads the formula a character at a time. 
-- When a variable is found using the case statement, it is queried in the value 
-- table and it's value is returned. Otherwise the operator is returned. This 
-- results in a row for each character in the formula. 
new_formula_tbl(id, new_formula) as (
    select level, case regexp_substr(formula, '(.|$)', 1, level, NULL, 1) 
     when 'x' then 
     (select x from val_tbl) 
     when 'y' then 
     (select y from val_tbl) 
     when 'z' then 
     (select z from val_tbl) 
     else regexp_substr(formula, '(.|$)', 1, level, NULL, 1) 
     end 
    from formula_tbl 
    connect by level <= regexp_count(formula, '.') 
) 
-- select id, new_formula from new_formula_tbl; 
-- This puts the rows back into a single string. Order by id (level) to keep operands 
-- and operators in the right order. 
select listagg(new_formula) within group (order by id) formula 
from new_formula_tbl; 

    FORMULA 
---------- 
    10-15+20 

또한 당신이 listagg을 전달하여 수식 결과를 얻을 수있다()() 함수는 다음 XMLQUERY에 전화 :

select xmlquery(replace(listagg(new_formula) within group (order by id), '/', ' div ') 
     returning content).getNumberVal() as result 
from new_formula_tbl; 

    RESULT 
---------- 
     15