在PostgreSQL中,如何将最后一个id插入表中?
在MS SQL中有SCOPE_IDENTITY().
请不要建议我使用这样的东西:
select max(id) from table
Run Code Online (Sandbox Code Playgroud) 如何将查询结果分配给PL/pgSQL中的变量,这是PostgreSQL的过程语言?
我有一个功能:
CREATE OR REPLACE FUNCTION test(x numeric)
RETURNS character varying AS
$BODY$
DECLARE
name character varying(255);
begin
name ='SELECT name FROM test_table where id='||x;
if(name='test')then
--do somthing
else
--do the else part
end if;
end;
return -- return my process result here
$BODY$
LANGUAGE plpgsql VOLATILE
Run Code Online (Sandbox Code Playgroud)
在上面的函数中我需要存储此查询的结果:
'SELECT name FROM test_table where id='||x;
Run Code Online (Sandbox Code Playgroud)
到变量name.
怎么处理这个?
database postgresql stored-procedures plpgsql postgresql-9.1
对于表B,有一个名为a_id的列,它是表A的ID。因此a_id是指向表a的外键,但它只是一个整数列,并且没有设置外键约束。
对于表B中的每一行,我们需要通过在表A中创建新记录来为a_id列提供一个整数值。
在一个SQL中完成以下所有步骤的目标。
将所有数据插入表A:
insert into table A (name) values ('abc'), ('def'), ... returning id
使用步骤1返回的ID(每个ID仅应使用一次)对表B中每一行的Buck更新a_id。
update table B set a_id = id(from previous insert statement)
尝试过类似的方法:
更新表B set a_id =(从ia中选择ia.id
(插入表A(名称)值('abc'),('def'),...返回ID)为ia)
但这会带来语法错误ERROR: syntax error at or near "into"。
如何用一个SQL做到这一点?