序列ID我這樣做:選擇/顯示最後插入在SQL Server的Postgres
insert into foo(name) values('bob')
select @@identity;
,所以我得到的查詢/標量結果顯示
如何將此與Postgres的?
序列ID我這樣做:選擇/顯示最後插入在SQL Server的Postgres
insert into foo(name) values('bob')
select @@identity;
,所以我得到的查詢/標量結果顯示
如何將此與Postgres的?
這將是
GET DIAGNOSTICS YourParam = RESULT_OID;
請看這裏http://www.postgresql.org/docs/8.2/static/plpgsql-statements.html向下滾動到37.6.6。獲取結果狀態
提問者編輯: 我嘗試這樣做:
create or replace function aaa() returns int as $$
declare
a int;
begin
insert into oameni values(default, 'aaa');
get diagnostics a = result_oid;
return a;
end;
$$ language plpgsql;
它總是返回0,你知道什麼是錯在這裏?
獲取特定的順序:
SELECT currval('name_of_your_sequence');
獲取從最後一個序列的最後一個值使用:
SELECT lastval();
檢查手冊,以及:http://www.postgresql.org/docs/current/static/functions-sequence.html
編輯:您還可以使用返回您的INSERT:
INSERT INTO foo(id, name) VALUES(DEFAULT, 'bob') RETURNING id;
一個好方法是使用RETURNING ID。這裏是使用PL/pgSQL的一個簡短例子:
DECLARE
nivel1 RECORD;
resultId BIGINT;
BEGIN
FOR nivel1 IN SELECT * FROM primary_table LOOP
INSERT INTO second_table(id, field2, field3) VALUES (DEFAULT, "value2", "value3") RETURNING id INTO resultId;
RAISE NOTICE 'Inserted id: %s', quote_literal(resultId);
END LOOP;
RETURN;
END
它適合我!
不要在SQL Server中使用'@@ identity'。使用[SCOPE_IDENTITY()](http://msdn.microsoft.com/en-us/library/ms190315.aspx)反而更安全,以避免觸發器的潛在問題。 – 2010-09-10 19:30:08