问题描述
这是一个sql Server查询,在Postgresql中如何实现?
DECLARE @p_key as int= NEXT VALUE FOR ProductSequence;
INSERT INTO Product(ID,Name,Price) VALUES(@p_key,@Name,@Price);
INSERT INTO ProductInfo(ID,Guid,DateCreation,DateLastChange,AgentCreationID,AgentLastChangeID) VALUES(@p_key,@Guid,@DateCreation,@DateLastChange,@AgentCreationID,@AgentLastChangeID);
SELECT @p_key;
解决方法
假设product.id
被定义为identity
,则可以使用可写的CTE来实现:
with new_product as (
insert into product (name,price)
values (...)
returning id
)
insert into product_info (id,guid,date_creation,date_last_change,anget_creation_id,agent_last_change_id )
select id,'guid',...
from new_product;
否则,只需使用nextval()
和lastval()
insert into product
(id,name,price)
values
(nextvalue('product_id_seq'),...);
insert into product_info
(id,agent_last_change_id )
values
(lastval(),....);