I don’t know how to write stored procedures in postgresql. I tried to write one and I’m getting the wrong output.
create or replace function getUserId() returns setof integer as
$BODY$
Declare r integer;cnt integer;
BEGIN
for r in select distinct user_id from system_audit
loop
for cnt in select count(*) from system_audit where user_id=r
loop
return next cnt;
end loop;
return next r;
end loop;
return;
end;
$BODY$
language 'plpgsql';
When I check the output by typing:-
select * from getUserId()
I get this as the Output:-
58
173
920
106
76
191
14413
1
2
242
1320
-1
2
249
1167
192
2
233
70
98
229
193
45
237
49
103
45735
115
10
201
28
167
308
96
1211
110
7
172
7
13
1614
22
16
178
21
170
7364
99
308
225
13
235
7
199
14
88
23566
118
359
4
9
231
98
165
174
212
21
149
14
105
77
97
416
180
1345
23
59
152
297
239
37
197
133
144
The output is correct But the problem is this is coming as a single column which contains the output of two columns- user_id and count. I want to see my output as two columns, one for count and another for user_id. Please help me finding the solution.
Thanks in advance!
You need to declare the function as
returns table (...)if you want to get a real result set.Your approach is overly complicated and will be extremely slow with large tables. The whole result can be obtained with a single SQL statement, which does not require looping with cursors:
This can be put into a SQL function (note: not plpgsql):
Note that the use of quoted language names is deprecated. You should use e.g.
plpgsqlinstead of'plpgsql'orsqlinstead of'sql'.