0

我有一个“code_table”,其中包含成对的 uinque 整数(code)和唯一文本(name)。我有几张表,其中有代码,但没有名称。我想创建一个函数来返回我打算更改的表,但它还添加了一个名称与代码匹配的列。我可以一一进行管理,但我需要一个带有表名参数的函数。

例如,这是一个code_table

code     name
(int)    (text)
1    ;  "Blue"
2    ;  "Yellow"
3    ;  "Red"
4    ;  "Green"
5    ;  "Purple"
6    ;  "Black"
7    ;  "White"
8    ;  "Gray"

我还有一个示例表 - table1

id  something  code
(int) (text) (int)
1 ; "someinfo" ; 4
2 ; "someinfo" ; 2
3 ; "someinfo" ; 6
4 ; "someinfo" ; 1
5 ; "someinfo" ; 8
6 ; "someinfo" ; 4
7 ; "someinfo" ; 2
8 ; "someinfo" ; 2
9 ; "someinfo" ; 3

我创建了一个没有返回值的函数,但它做了我想要的:

CREATE FUNCTION add_code_name() 
RETURNS VOID AS
$BODY$
BEGIN
    ALTER TABLE table1 ADD name text;
    EXECUTE 'UPDATE table1 SET name = code_table.name FROM code_table WHERE table1.code = code_table.code';
END;
$BODY$
LANGUAGE plpgsql;

结果我得到:

id  something  code name
(int) (text) (int) (text)
1 ; "someinfo" ; 4 ; "Green"
2 ; "someinfo" ; 2 ; "Yellow"
3 ; "someinfo" ; 6 ; "Black"
4 ; "someinfo" ; 1 ; "Blue"
5 ; "someinfo" ; 8 ; "Gray"
6 ; "someinfo" ; 4 ; "Green"
7 ; "someinfo" ; 2 ; "Yellow"
8 ; "someinfo" ; 2 ; "Yellow"
9 ; "someinfo" ; 3 ; "Red"

我的问题:有没有办法以某种方式将表的名称放在函数参数中,所以它会对我的任何表做同样的事情?另外,我会在其中放置包含代码的列的名称,如下所示:

add_code_name(table1.code) 

谢谢您的帮助!

4

1 回答 1

1

这是一个执行更改和更新的函数:

create or replace function add_code_name(rel text, code_col text)
returns void as 
$Body$
begin
    execute 'ALTER TABLE '||quote_ident(rel)||' ADD name text';
    execute 'UPDATE '||quote_ident(rel)||' SET name = code_table.name FROM code_table WHERE '||quote_ident(rel)||'.'||quote_ident(code_col)||' = code_table.code';

    return;
end;
$Body$
language plpgsql; 

你运行它:

select add_code_name('table1', 'code');
于 2020-03-30T14:37:15.060 回答