Home > Database > Mysql Tutorial > How Do I Effectively Use Variables in PostgreSQL's psql?

How Do I Effectively Use Variables in PostgreSQL's psql?

DDD
Release: 2025-01-15 11:20:44
Original
151 people have browsed it

How Do I Effectively Use Variables in PostgreSQL's psql?

Using script variables in PostgreSQL's psql

The way custom scripts use variables in PostgreSQL is different from MS SQL Server. In psql, use the set command to create variables:

<code class="language-sql">\set myvariable value</code>
Copy after login

To replace variables in a query, use the following syntax:

<code class="language-sql">SELECT * FROM :myvariable.table1;</code>
Copy after login

Alternatively, you can use it in a conditional statement:

<code class="language-sql">SELECT * FROM table1 WHERE :myvariable IS NULL;</code>
Copy after login

Starting with psql 9.1, variables can be expanded within quotes:

<code class="language-sql">\set myvariable value
SELECT * FROM table1 WHERE column1 = :'myvariable';</code>
Copy after login

In versions prior to psql 9.1, when using variables in conditional string queries, for example:

<code class="language-sql">SELECT * FROM table1 WHERE column1 = ':myvariable';</code>
Copy after login

Need to include quotes around the variable itself:

<code class="language-sql">\set myvariable 'value'</code>
Copy after login

For string manipulation, consider the following tips:

<code class="language-sql">\set quoted_myvariable '\'' :myvariable '\''</code>
Copy after login

This creates quoted and unquoted variables of the same string, allowing you to do the following:

<code class="language-sql">INSERT INTO :myvariable.table1 SELECT * FROM table2 WHERE column1 = :quoted_myvariable;</code>
Copy after login

The above is the detailed content of How Do I Effectively Use Variables in PostgreSQL's psql?. 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