Example: Create function in Postgresql

创建用户自定义函数或者存储过程,这种事在SQL Server下面我们已经司空见惯了。但是在Postgresql下,我们还是要熟悉一下PL/pgSQL的语法。

 

相关表结构:

 

Example: Create function in Postgresql_第1张图片

写一个Function来插入suiteId和caseId,保证这两个Id都能正确关联到TestSuite表和TestCase表:

 

Create or Replace function func_TestSuite_AddTestCase(sid INTEGER, cid INTEGER) returns INTEGER as $funcbody$ Declare checker BOOLEAN; Declare cnt INTEGER; Begin -- Check if input parameter sid is exist in table testsuite select count(id) into cnt from testsuite where id = $1; if cnt <> 1 then return -101; end if; -- Check if input parameter cid is exist in table testcase select count(id) into cnt from testcase where id = $2; if cnt <> 1 then return -102; end if; -- Check if sid and cid pair is exist in table testsuitecase select count(*) into cnt from testsuitecase where suiteid = $1 and caseid = $2; if cnt <> 1 then insert into testsuitecase(suiteid, caseid) values($1, $2); -- Check if the insertion command is executed successfully. select count(*) into cnt from testsuitecase where suiteid = $1 and caseid = $2; if cnt <> 1 then return -2; end if; return 1; else -- the value you want to input is duplicated in table testsuitecase return -1; end if; End; $funcbody$ LANGUAGE plpgsql;

 

$1、$2的用法看上去还是挺爽的。

 

你可能感兴趣的:(sql,function,server,table,Integer,PostgreSQL,input)