在plpgsql函数中执行sql

时间:2014-05-14 14:44:40

标签: sql postgresql plpgsql

使用postgreSQL 9.1.9,我有一些像这样的SQL请求:

 INSERT INTO "my_table" VALUES(10,'James','California');

下面是原始名称查找表的简化表...

  names

  name_id      name
  ---          -----
  3            James

但实际上我不必输入(进入“my_table”)SQL请求提供的文本值(人名,状态名称),但其对应的ID位于另一个表中(例如:名称表) )

所以我在考虑创建一个触发器,调用一个应该执行select SQL请求的函数并返回要插入的修改行。

这可能吗?

CREATE FUNCTION insert_by_ID() RETURNS TRIGGER AS '

        BEGIN
            --Can we execute this query, store the result in a variable to be added
              to the NEW record?

            SELECT name_id from names where name=NEW.name;

                           --this request would be...
                           --SELECT name_id from names where name='James'     
          RETURN NEW;
        END;
        ' LANGUAGE plpgsql;

CREATE TRIGGER insert_info_ID
        BEFORE INSERT ON my_table
        FOR EACH ROW
        EXECUTE PROCEDURE insert_by_ID();

1 个答案:

答案 0 :(得分:1)

我有根据的猜测是你想要一个“SELECT or INSERT if not exists”问题的解决方案。

我建议您创建一个像这样的plpgsql函数:

CREATE OR REPLACE FUNCTION f_name_id(_name text, OUT _name_id int) AS
$func$
BEGIN

LOOP
   BEGIN

   SELECT name_id FROM names WHERE name = _name FOR SHARE   -- lock!
   INTO  _name_id;

   IF NOT FOUND THEN
      INSERT INTO names (name) VALUES (_name) RETURNING name_id
      INTO  _name_id;
   END IF;

   EXCEPTION WHEN UNIQUE_VIOLATION THEN      -- inserted concurrently!
      RAISE NOTICE 'It actually happened!';  -- hardly ever happens
   END;

   EXIT WHEN _name_id IS NOT NULL;           -- else try again
END LOOP;

END
$func$ LANGUAGE plpgsql;

这是一个简单版本(更多解释和链接):
Is SELECT or INSERT in a function prone to race conditions?

INSERT

然后您的INSERT语句可能如下所示:

INSERT INTO my_table(my_table_id, name_id, state) -- always with column list
VALUES (10, f_name_id('James'), 'California');