pgsql comment
时间: 2025-06-06 13:15:06 浏览: 15
### PostgreSQL 注释功能与语法
在 PostgreSQL 中,注释可以分为两种类型:单行注释和多行注释。此外,PostgreSQL 提供了对象级别的注释功能,允许用户为数据库对象(如表、列、函数等)添加描述性注释。
#### 单行注释
单行注释以双短横线 `--` 开头,后续内容直到行尾都会被视为注释[^1]。
```sql
-- 这是一个单行注释
SELECT 3 * 7;
```
#### 多行注释
多行注释使用 `/* */` 包裹,可以跨越多行。这种注释方式适用于较长的说明或代码块中的临时屏蔽[^2]。
```sql
/*
这是一个多行注释
可以跨越多行
*/
SELECT 3 * 7;
```
#### 对象级别的注释
PostgreSQL 提供了 `COMMENT ON` 命令,用于为数据库对象添加注释。这些注释存储在系统目录中,可以通过 `\d` 命令查看[^3]。
以下是常见的 `COMMENT ON` 语法:
```sql
COMMENT ON TABLE table_name IS 'This is a comment on the table';
COMMENT ON COLUMN table_name.column_name IS 'This is a comment on the column';
```
例如,为一个表和其列添加注释:
```sql
CREATE TABLE example (
id SERIAL PRIMARY KEY,
name TEXT
);
COMMENT ON TABLE example IS 'This is an example table for demonstration purposes.';
COMMENT ON COLUMN example.id IS 'Primary key for the example table.';
```
通过 `\d` 命令可以查看表及其列的注释:
```sql
\d example
```
输出可能如下:
```
Table "public.example"
Column | Type | Modifiers | Storage | Description
--------+---------+-----------------+----------+-------------
id | integer | not null | plain | Primary key for the example table.
name | text | | extended |
Description:
This is an example table for demonstration purposes.
```
### 示例代码
以下是一个完整的示例,展示如何使用注释功能:
```sql
-- 创建一个示例表
CREATE TABLE products (
product_id SERIAL PRIMARY KEY,
product_name TEXT NOT NULL,
price NUMERIC(10, 2)
);
-- 为表添加注释
COMMENT ON TABLE products IS 'This table stores information about products.';
-- 为列添加注释
COMMENT ON COLUMN products.product_id IS 'Unique identifier for each product.';
COMMENT ON COLUMN products.product_name IS 'Name of the product.';
COMMENT ON COLUMN products.price IS 'Price of the product in USD.';
-- 查看表及其注释
\d products
```
阅读全文
相关推荐


















