pg custom function

Sometimes we encounter some more complex statements in the database update data operation, instead of simple update xxx set xx = aa where ...

What we encounter may be updating a column of data in the database, and inserting a random value from a given value. At this time, ordinary update statements can no longer meet our needs. Then the custom function helps a lot.

1. Scenario assumption: We need to add a column called color to the tag table, and randomly add color values ​​to the existing tags (all color values ​​have been given). First we need to write a custom function getRandomColor to get random color values:

drop function getRandomColor;
create or replace function getRandomColor()
    returns varchar
as
$$
declare
    color varchar;
    colors varchar[];
    num int;
begin
    colors := array ['#1', '#2', '#3',
                     '#4', '#5', '#6'];
    num := floor(random()*(6-1)+1);
    color := colors[num];
    return color;
end ;
$$ language plpgsql;

Since I have to test repeatedly, I added a delete method to the first sentence. Then I also fixed 6 color values ​​and replaced them with "#123456" for easy distinction, which is not a real color value.

2. After the function is written, how to call it naturally is very easy. We can directly use the method name in the SQL statement:

update train_task_tag set color = getRandomColor() where id in ('TTAGa49ef38611eca7b1b63e34a44cb5', 'TTAG46eaf38911eca7b1b63e34a44cb5');

3. View the effect:

before fixing:

After modification: 

 OK, you're done!

Supongo que te gusta

Origin blog.csdn.net/wangyuntuan/article/details/128718805
Recomendado
Clasificación