Home > Database > Mysql Tutorial > How Can I Use Variables and Retrieve the Last Inserted ID in PostgreSQL?

How Can I Use Variables and Retrieve the Last Inserted ID in PostgreSQL?

DDD
Release: 2025-01-24 20:18:11
Original
704 people have browsed it

How Can I Use Variables and Retrieve the Last Inserted ID in PostgreSQL?

PostgreSQL script variable

In MS-SQL, you can use the DeCLARE keyword to declare and use variables in the query window. This allows you to store and operate data dynamically. For example, you can declare a variable called @list and assign a value, and then use it in the Select statement to retrieve the data based on the value of the variable.

Use variables in PostgreSQL

To implement similar functions in PostgreSQL, you can use the new anonymous code block function introduced in version 9.0. This feature allows you to execute code blocks in a SQL statement.

Example:

Get the last inserted ID
<code class="language-sql">DO $$
DECLARE v_List TEXT;
BEGIN
  v_List := 'foobar' ;
  SELECT *
  FROM   dbo.PubLists
  WHERE  Name = v_List;
  -- ...
END $$;</code>
Copy after login

You can also use this code block function to retrieve the last inserted ID after the INSERT operation:

Please refer to the official PostgreSQL document to understand the complete discussion of using variables in the PostgreSQL script.
<code class="language-sql">DO $$
DECLARE lastid bigint;
BEGIN
  INSERT INTO test (name) VALUES ('Test Name') 
  RETURNING id INTO lastid;

  SELECT * FROM test WHERE id = lastid;
END $$;</code>
Copy after login

The above is the detailed content of How Can I Use Variables and Retrieve the Last Inserted ID in PostgreSQL?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template