最近学习postgresql,正一个小活要用上,所以就开始学习了!
然而,学习的过程极其艰辛,但却也充满了乐趣.
一般来说数据库的操作不外如何增,删,改,查,
而首要的就是要添加数据到数据库中,因为以前的经验,
存储过程要比不用存储过程效率要高不少,至少我的程序环境是这样的结果!
所以就想要做写些存储过程,如果一个表一个存储过程,那仅存储过程就得写好几百个
这个实是有点夸张了!(这还仅是插入.加上删除/修改/查询那得近上千)
那么能不能有个方法,可以减少工作量呢?自动根据表名,字段名及字段值与插入?
POSTGRESQL 真的很强大!虽然我还没有入门!
这个问题我通过测试看函数花了三整天,总算有点眉目:
干货直接拉到最后看最后一个插入存储过程.
下面是我的学习过程,本不想加上,可这是我一步步的做过来的.
-- 目标:动态插入表中数据 -- 老规矩上代码 -- 插入函数如下 ---------------------------------------- CREATE OR REPLACE FUNCTION f_insert_module_string( modulename text, feildname text[], feildvalue text[], out returnValue text ) AS $$ DECLARE myid integer; ex_result integer default 0; ex_sql text; BEGIN myid:=f_getNewID(modulename,'id'); ex_sql:='insert into ' ||quote_ident(moduleName) ||'(id,' ||array_to_string(feildname,',') ||') values('||myid||',''' ||array_to_string(feildvalue,''',''') ||''')'; execute ex_sql; GET DIAGNOSTICS ex_result:= ROW_COUNT; if ex_result<>0 then returnValue:='{"SUCCESS":"插入操作'||ex_sql||'成功!"}'; else returnValue:='{"ERROR":"插入操作'||ex_sql||'失败!"}'; end if; END; $$ language plpgsql; -- 实际操作 select f_insert_module_string('test','{name,code,gen_time}','{whq,111000,2018-08-20}'); -- 得到如下结果:
--同样,在插入时,直接用单引号把日期给引起来,INSERT 也不会报错,
--那么如果用C#调用存储过程会不会报错呢?
--我们拭目以待!
------------------------------
--经测试没有问题!
--下面是测试过程及改进代码 --=================================================== --插入数据除了 id ,其余字段全部以TEXT 格式传递 --modulename 即为表名 --feildname 即为字段名 --feildvalue 即为对应的字段值(插入时全部为text) --这里的字段名和字段值是一一对应的关系,否则出错 --=================================================== CREATE OR REPLACE FUNCTION f_insert_module_string( modulename text, feildname text[], feildvalue text[], out returnValue text ) AS $$ DECLARE myid integer; ex_result integer default 0; ex_sql text; BEGIN myid:=f_getNewID(modulename,'id'); ex_sql:='insert into ' ||quote_ident(moduleName) ||'(id,' ||array_to_string(feildname,',') ||') values('||myid||',''' ||array_to_string(feildvalue,''',''') ||''')'; execute ex_sql; GET DIAGNOSTICS ex_result:= ROW_COUNT; if ex_result<>0 then returnValue:='{"SUCCESS":"插入操作'||ex_sql||'