Home >Database >Mysql Tutorial >How Can I Use Variables in PostgreSQL Like I Do in Microsoft SQL Server?

How Can I Use Variables in PostgreSQL Like I Do in Microsoft SQL Server?

DDD
DDDOriginal
2025-01-24 20:34:12748browse

How Can I Use Variables in PostgreSQL Like I Do in Microsoft SQL Server?

PostgreSQL Variable Usage: A Practical Guide

Microsoft SQL Server's convenient variable handling within query windows is mirrored in PostgreSQL, albeit with a slightly different approach. This guide demonstrates how to declare, assign, and utilize variables within PostgreSQL scripts.

Declaring and Using Variables in PostgreSQL

PostgreSQL employs the DO $$ anonymous code block for variable declaration and manipulation. This allows you to define variables with specific data types and assign them values. The following example illustrates this:

<code class="language-sql">DO $$
DECLARE v_Name TEXT;
BEGIN
  v_Name := 'foobar';
  SELECT * FROM dbo.PubLists WHERE Name = v_Name;
  -- Further operations using v_Name
END $$;</code>

Retrieving the Last Inserted ID

A common task is retrieving the ID of the last inserted row. PostgreSQL efficiently handles this using the RETURNING clause within the INSERT statement, as shown below:

<code class="language-sql">DO $$
DECLARE last_inserted_id BIGINT;
BEGIN
  INSERT INTO test (name) VALUES ('Test Name')
  RETURNING id INTO last_inserted_id;

  SELECT * FROM test WHERE id = last_inserted_id;
END $$;</code>

This concise method demonstrates the power and flexibility of variable usage within PostgreSQL, offering functionality comparable to Microsoft SQL Server's variable handling.

The above is the detailed content of How Can I Use Variables in PostgreSQL Like I Do in Microsoft SQL Server?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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