PostgreSQL 9.3:准备动态字符串

时间:2015-03-20 06:33:50

标签: sql string postgresql postgresql-9.3

我想使用该函数准备动态字符串。

这里有两个主要的叮咬:一个是传递给函数和 另一个存在于函数中。输出字符串将更改 根据传递给函数的字符串。

示例

我有字符串string1,它将传递给该函数。 string2 存在于函数中。

函数中存在一个string2字符串:

string2 = 'A1,A2,A3,A4'

字符串string1我传递给函数:

string1 = 'A1'

然后预期准备好的字符串看起来像:

A1 = 1 AND A2 IS NULL AND A3 IS NULL AND A4 IS NULL

对于上面的结果,我编写了folling函数:

CREATE OR REPLACE FUNCTION f_test(string1 varchar)
RETURNS VOID AS
$$
DECLARE
    string2 varchar = 'A1,A2,A3,A4';
    string3 varchar;
    string4 varchar;
    string5 varchar;
    string6 varchar;
BEGIN
    string3 := REPLACE(string1,',',' = 1 AND ')||' = 1';

    RAISE INFO '%',string3;

    string4 := REPLACE(string2,string1,string3);

    RAISE INFO '%',string4; 

    string5 := REPLACE(string4,'1,',' 1 AND ');

    string6 := REPLACE(string5,',', ' IS NULL AND ')||' IS NULL ';

    RAISE INFO '%',string6; 
END;
$$
LANGUAGE PLPGSQL;

调用功能

SELECT f_test('A1');

结果:(右)

A1 =  1 AND A2 IS NULL AND A3 IS NULL AND A4 IS NULL 

在通过A4

时卡住了
SELECT f_test('A4');

结果:(错)

A 1 AND A2 IS NULL AND A3 IS NULL AND A4 =  1 

虽然我在期待:

A1 IS NULL AND A2 IS NULL AND A3 IS NULL AND A4 =  1 

如果我打电话:

SELECT f_test('A2,A4');

然后结果应该是:

A1 IS NULL AND A2 = 1 AND A3 IS NULL AND A4 =  1 

1 个答案:

答案 0 :(得分:1)

试试这个

CREATE OR REPLACE FUNCTION f_test(string1 varchar)
RETURNS VOID AS
$$
DECLARE
    string2 varchar = 'A1,A2,A3,A4,A5,A6,A7';
    string3 varchar;
    string4 varchar;
    string5 varchar;
    string6 varchar;
    intCount int;
BEGIN
    string3 := REPLACE(string1,',',' = 1 AND ')||' = 1';

    RAISE INFO '%',string3;

    string4 := REPLACE(string2,string1,string3);

    RAISE INFO '%',string4; 
select string_agg(c,' AND ') into  string6 from (
select  * from (
select c ||'= 1' c from (
select regexp_split_to_table(string2,',') c
)t 
where c in (select regexp_split_to_table(string1,','))
union all 
select c ||' IS NULL ' c from (
select regexp_split_to_table(string2,',') c
)t 
where  c  not in (select regexp_split_to_table(string1,','))
) t group by c order by c 
)t;
    RAISE INFO '%',string6; 
END;
$$
LANGUAGE PLPGSQL;

致电: - select f_test('A3,A5')select f_test('A3,A5,A2,A6')