1 --建表
2 CREATE TABLE user_friend
3 (
4 uf_id serial NOT NULL,
5 uf_userid integer NOT NULL,
6 uf_friendlist character varying(1000),
7 uf_created timestamp without time zone DEFAULT now(),
8 uf_count integer,
9 uf_listname character varying(1000),
10 CONSTRAINT pk_user_friend PRIMARY KEY (uf_id)
11 );
12 --新建一个函数,用于用户添加和插入数据
13 CREATE OR REPLACE FUNCTION add_friend(userid INT, friend_userid INT, friend_name character varying) RETURNS INT AS
14 $$
15 BEGIN
16 LOOP
17 -- first try to update the key
18 UPDATE user_friend set uf_friendlist = replace(uf_friendlist, ','||friend_userid||',', ',')||friend_userid||',', uf_listname = replace(uf_listname, ','||friend_name||',', ',')||friend_name||',',uf_count = length(uf_friendlist) - length(REPLACE(uf_friendlist, ',', '')) - 1 where uf_userid=userid;
19 IF found THEN
20 RETURN 1;
21 END IF;
22
23 BEGIN
24 INSERT INTO user_friend(uf_userid,uf_friendlist,uf_count,uf_listname) VALUES (userid, ','||friend_userid||',',1,','||friend_name||',');
25 RETURN 2;
26 EXCEPTION WHEN unique_violation THEN
27 RETURN 0;
28 -- do nothing, and loop to try the UPDATE again
29 END;
30 END LOOP;
31 END;
32 $$
33 LANGUAGE plpgsql;
34
35 --添加
36 select add_friend(1,1,'wangbin1');
37 select add_friend(1,2,'wangbin2');
38 select add_friend(2,1,'wangbin1');
39 select add_friend(2,2,'wangbin2');
40 select add_friend(3,1,'wangbin1');
41 select add_friend(3,2,'wangbin2');