将UUID值作为参数传递给函数 [英] Pass UUID value as a parameter to the function

查看:425
本文介绍了将UUID值作为参数传递给函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的表中有一些列:

--table
create table testz
(
   ID uuid,
   name text
);

注意:我要插入 ID 值作为参数传递给函数。因为我通过使用 uuid_generate_v4()在前端生成 ID
。因此,我需要将生成的值传递给函数,以将
插入表中

Note: I want to insert ID values by passing as a parameter to the function. Because I am generating the ID value in the front end by using uuid_generate_v4(). So I need to pass the generated value to the function to insert into the table

--function
CREATE OR REPLACE FUNCTION testz
(
    p_id varchar(50),
    p_name text
)
RETURNS VOID AS
$BODY$
BEGIN
    INSERT INTO testz values(p_id,p_name);
END;
$BODY$
LANGUAGE PLPGSQL;

--EXECUTE FUNCTION
SELECT testz('24f9aa53-e15c-4813-8ec3-ede1495e05f1','Abc');

出现错误:

ERROR:  column "id" is of type uuid but expression is of type character varying
LINE 1: INSERT INTO testz values(p_id,p_name)


推荐答案

您需要简单的强制转换以确保PostgreSQL理解要插入的内容:

You need a simple cast to make sure PostgreSQL understands, what you want to insert:

INSERT INTO testz values(p_id::uuid, p_name); -- or: CAST(p_id AS uuid)

或者(最好)您需要一个函数,精确参数类型,例如:

Or (preferably) you need a function, with exact parameter types, like:

CREATE OR REPLACE FUNCTION testz(p_id uuid, p_name text)
RETURNS VOID AS
$BODY$
BEGIN
    INSERT INTO testz values(p_id, p_name);
END;
$BODY$
LANGUAGE PLPGSQL;

这样,在调用方可能需要强制转换(但是PostgreSQL通常使用函数参数而不是 INSERT 语句内部)。

With this, a cast may be needed at the calling side (but PostgreSQL usually do better automatic casts with function arguments than inside INSERT statements).

SQLFiddle

如果您的函数很简单,则可以使用 SQL 函数

If your function is that simple, you can use SQL functions too:

CREATE OR REPLACE FUNCTION testz(uuid, text) RETURNS VOID
LANGUAGE SQL AS 'INSERT INTO testz values($1, $2)';

这篇关于将UUID值作为参数传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆