Pass UUID value as a parameter to the function

僤鯓⒐⒋嵵緔 提交于 2019-12-02 15:40:37

问题


I have the table with some columns:

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

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

My bad try:

--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');

Getting an error:

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

回答1:


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;

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

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)';


来源:https://stackoverflow.com/questions/27900060/pass-uuid-value-as-a-parameter-to-the-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!