

 从补丁 198 开始，Amazon Redshift 将不再支持创建新的 Python UDF。现有的 Python UDF 将继续正常运行至 2026 年 6 月 30 日。有关更多信息，请参阅[博客文章](https://aws.amazon.com/blogs/big-data/amazon-redshift-python-user-defined-functions-will-reach-end-of-support-after-june-30-2026/)。

# 通过客户端工具和代码连接
<a name="connecting-via-client-tools"></a>

Amazon Redshift 提供 Amazon Redshift 查询编辑器 v2，用于连接到您的集群和工作组。有关更多信息，请参阅 [使用查询编辑器 v2 查询数据库使用 Amazon Redshift 查询编辑器 v2 查询数据库](query-editor-v2.md)。

此部分提供了一些用于第三方工具连接的选项。另外，此部分还介绍了如何以编程方式连接到您的集群。

**Topics**
+ [使用 Amazon Redshift RSQL 连接](rsql-query-tool.md)
+ [使用 Amazon Redshift RSQL 连接到集群](rsql-query-tool-starting-tool-connection.md)
+ [Amazon Redshift RSQL 元命令](rsql-query-tool-commands.md)
+ [Amazon Redshift RSQL 变量](rsql-query-tool-variables.md)
+ [Amazon Redshift RSQL 错误代码](rsql-query-tool-error-codes.md)
+ [Amazon Redshift RSQL 环境变量](rsql-query-tool-environment-variables.md)

# 使用 Amazon Redshift RSQL 连接
<a name="rsql-query-tool"></a>

 Amazon Redshift RSQL 是一个命令行客户端，用于与 Amazon Redshift 集群和数据库进行交互。您可以连接到 Amazon Redshift 集群、描述数据库对象、查询数据以及查看各种输出格式的查询结果。

 Amazon Redshift RSQL 支持 PostgreSQL psql 命令行工具的功能以及特定于 Amazon Redshift 的额外功能。这些功能包括：
+ 您可以使用 AD FS、PingIdentity、Okta、Azure ADm 或其它基于 SAML/JWT 的身份提供者实现单点登录身份验证。您还可以使用基于浏览器的 SAML 身份提供者进行多重身份验证（MFA）。
+ 您可以描述 Amazon Redshift 对象的特性或属性，例如表分发键、表排序键、后期绑定视图（LBV）和实体化视图。您还可以描述 AWS Glue 目录或 Apache Hive Metastore 中外部表的特性或属性、Amazon RDS for PostgreSQL、Amazon Aurora PostgreSQL 兼容版、RDS for MySQL（预览版）和 Amazon Aurora MySQL 兼容版（预览版）中的外部数据库，以及使用 Amazon Redshift 数据共享共享的表。
+ 您还可以使用增强的控制流命令，例如 `IF`（`\ELSEIF`、`\ELSE,` `\ENDIF`）`\GOTO` 和 `\LABEL`。

 借助 Amazon Redshift RSQL 批处理模式（运行作为输入参数传递的脚本），您可以运行包含 SQL 和复杂业务逻辑的脚本。如果您有现有的自我管理的本地数据仓库，您可以使用 Amazon Redshift RSQL 替换现有的提取、转换、加载（ETL）和自动化脚本，例如 Teradata BTEQ 脚本。使用 RSQL 有助于避免以过程语言手动重新实现脚本。

 Amazon Redshift RSQL 适用于 Linux、Windows 和 macOS X 操作系统。

如需报告 Amazon Redshift RSQL 的问题，请发送邮件至 redshift-rsql-support@amazon.com。

**Topics**
+ [Amazon Redshift RSQL 入门](rsql-query-tool-getting-started.md)
+ [Amazon Redshift RSQL 更改日志](rsql-query-tool-changelog.md)

# Amazon Redshift RSQL 入门
<a name="rsql-query-tool-getting-started"></a>

在具有 Linux、macOS 或微软 Windows 操作系统的计算机上安装 Amazon Redshift RSQL。

## 下载 RSQL
<a name="rsql-query-tool-download"></a>
+ Linux 64 位 RPM：[RSQL 版本 1.1.2](https://s3.amazonaws.com/redshift-downloads/amazon-redshift-rsql/1.1.2/AmazonRedshiftRsql-1.1.2.rhel.x86_64.rpm)
  + Linux 构件签名密钥：[密钥](https://s3.amazonaws.com/redshift-downloads/amazon-redshift-rsql/1.1.2/AmazonRedshiftRsql-1.1.2-certificate.pem) 
  + Linux 构件签名哈希：[哈希](https://s3.amazonaws.com/redshift-downloads/amazon-redshift-rsql/1.1.2/AmazonRedshiftRsql-1.1.2-signature.bin) 
+ Mac OS 64 位 PKG：[RSQL 版本 1.1.2](https://s3.amazonaws.com/redshift-downloads/amazon-redshift-rsql/1.1.2/AmazonRedshiftRsql-1.1.2.universal.pkg)
+ Windows 64 位 MSI：[RSQL 版本 1.1.2](https://s3.amazonaws.com/redshift-downloads/amazon-redshift-rsql/1.1.2/AmazonRedshiftRsql-1.1.2.x86_64.msi)

请在 [Amazon Redshift RSQL 更改日志](rsql-query-tool-changelog.md)中参阅以前版本的更改日志和下载。

## 安装适用于 Linux 的 RSQL
<a name="rsql-query-tool-linux-install"></a>

请按照以下步骤，安装适用于 Linux 的 RSQL。

1. 使用以下命令安装驱动程序：

   ```
   sudo yum install unixODBC
   ```

1. 安装 ODBC 驱动程序：[下载并安装 Amazon Redshift ODBC 驱动程序下载并安装 ODBC 驱动程序](odbc20-install-linux.md)。

1. 将 ini 文件复制到您的主目录：

   ```
   cp /opt/amazon/redshiftodbcx64/odbc.ini ~/.odbc.ini
   ```

1. 将环境变量设置为指向文件的位置：

   ```
   export ODBCINI=~/.odbc.ini
   export ODBCSYSINI=/opt/amazon/redshiftodbcx64/
   export AMAZONREDSHIFTODBCINI=/opt/amazon/redshiftodbcx64/amazon.redshiftodbc.ini
   ```

1. 现在，您可以通过运行以下命令安装 RSQL。

   ```
   sudo rpm -i AmazonRedshiftRsql-<version>.rhel.x86_64.rpm
   ```

## 安装适用于 Mac 的 RSQL
<a name="rsql-query-tool-mac-install"></a>

请按照以下步骤操作，安装适用于 Mac OSX 的 RSQL。

1. 使用以下命令安装驱动程序：

   ```
   brew install unixodbc --build-from-source
   ```

1. 安装 ODBC 驱动程序：[下载并安装 Amazon Redshift ODBC 驱动程序下载并安装 ODBC 驱动程序](odbc-driver-mac-how-to-install.md)。

1. 将 ini 文件复制到您的主目录：

   ```
   cp /opt/amazon/redshift/Setup/odbc.ini ~/.odbc.ini
   ```

1. 将环境变量设置为指向文件的位置：

   ```
   export ODBCINI=~/.odbc.ini
   export ODBCSYSINI=/opt/amazon/redshift/Setup
   export AMAZONREDSHIFTODBCINI=/opt/amazon/redshift/lib/amazon.redshiftodbc.ini
   ```

1. 如果它不在`/usr/local/lib` 中，则将 `DYLD_LIBRARY_PATH` 设置为 libodbc.dylib 的位置。

   ```
   export DYLD_LIBRARY_PATH=$DYLD_LIBRARY_PATH:/usr/local/lib
   ```

1. 双击 pkg 文件运行安装程序。

1. 按照安装向导中的步骤完成安装。同意许可协议条款。

## 安装适用于 Windows 的 RSQL
<a name="rsql-query-tool-windows-install"></a>

请按照以下步骤操作，安装适用于 Windows 的 RSQL。

1. 安装 ODBC 驱动程序：[下载并安装 Amazon Redshift ODBC 驱动程序下载并安装 ODBC 驱动程序](odbc-driver-windows-how-to-install.md)。

1. 请双击 RSQL 下载文件，以运行安装程序，然后按照提示完成安装。

# Amazon Redshift RSQL 更改日志
<a name="rsql-query-tool-changelog"></a>

*1.1.2（2025-12-11）*

错误修复
+ 修复了一个错误，该错误会导致 \$1goto 和 \$1label 命令失败。
+ 修复了一个错误，当变量被引号引起来时，该错误会导致 RSQL 无法打印变量值。
+ 修复了一个错误，在启用 UseDeclareFetch 后，如果查询结果超过 ODBC DSN Fetch 参数大小，该错误会导致 RSQL 发生崩溃。
+ 修复了一个问题，即便已启用分页程序，该问题也会导致一次性返回多个结果页。
+ 修复了一个错误，在事务块内的查询失败时，该错误会导致 RSQL 发生崩溃。

*1.1.1（2025-11-20）*

错误修复
+ 修复了一个问题，在使用 -c 标志时，该问题会导致 RSQL 错误地解析查询。此修复适用于所有平台。
+ 修复了 Mac 上的一个错误，该错误导致用户无法在 RSQL 中使用 \$1s 命令。

*1.1.0（2025-11-11）*

错误修复
+ 解决了导致 RSQL 中意外发生崩溃的内存泄漏问题。
+ 从 RSQL 中移除了 OpenSSL 依赖项。
+ 修复了同一环境中的 libpq/psql 安装存在的链接冲突问题。
+ 提升了针对 Amazon Linux 2023、Windows 和 macOS 的平台兼容性。
+ 修复了一个问题，当输出超出当前显示大小时，该问题会导致输出被截断。

*1.0.8 (2023-06-19)*

错误修复
+ 修复了使用 SHOW 命令时会截断输出的问题。
+ 为 \$1de 添加了用于描述外部 Kinesis 流和 Kafka 主题的支持。

*1.0.7 (2023-03-22)*

错误修复
+ 修复了 RSQL 无法描述实体化视图的问题。
+ 修复了使用 Amazon Redshift Serverless 时 stl\$1connection\$1log 上出现的权限被拒绝错误。
+ 修复了 RSQL 可能不正确地处理 \$1GOTO 标签的问题。
+ 修复了在静默模式下输出 SSL 消息的问题。
+ 修复了描述存储过程时显示随机字符的问题。
+ 修复了重复输出 ERROR/INFO 消息的问题。

New
+ RSQL 现在可以直接从 ODBC 驱动程序获取 SSL 信息。



*1.0.6 (2023-02-21)*

错误修复
+ 修复了在 Redshift 补丁 1.0.46086 (P173) 上，\$1d 引发错误（整数的输入语法无效："xid"）的问题。

New
+ 已重命名安装文件来体现支持的架构。



*1.0.5（2022 年 6 月 27 日）*

错误修复
+ 将 SQL 错误消息发送到标准错误 (stderr)。
+ 修复了使用 ON\$1ERROR\$1STOP 时退出代码的问题。现在，脚本将在遇到错误后终止，并返回正确的退出代码。
+ Maxerror 现在不区分大小写。

New
+ 增加了对 ODBC 2.x 驱动程序的支持。



*1.0.4 (2022-03-19)*
+ 添加对 RSPASSWORD 环境变量的支持。设置密码以连接到 Amazon Redshift。例如 `export RSPASSWORD=TestPassw0rd`。



*1.0.3（2021 年 12 月 8 日）*

错误修复
+ 修复了在 Windows 操作系统中使用 `\c` 或 `\logon` 切换数据库时弹出的对话框。
+ 修复了检查 ssl 信息时发生的崩溃。



## Amazon Redshift RSQL 的以前版本
<a name="rsql-query-tool-changelog-legacy-versions"></a>

请根据您的操作系统，选择其中一个链接以下载所需的 Amazon Redshift RSQL 版本。

**Linux 64 位 RPM**
+ [RSQL 版本 1.1.1](https://s3.amazonaws.com/redshift-downloads/amazon-redshift-rsql/1.1.1/AmazonRedshiftRsql-1.1.1.rhel.x86_64.rpm)
+ [RSQL 版本 1.1.0](https://s3.amazonaws.com/redshift-downloads/amazon-redshift-rsql/1.1.0/AmazonRedshiftRsql-1.1.0.rhel.x86_64.rpm)
+ [RSQL 版本 1.0.8](https://s3.amazonaws.com/redshift-downloads/amazon-redshift-rsql/1.0.8/AmazonRedshiftRsql-1.0.8.x86_64.rpm)
+ [RSQL 版本 1.0.7](https://s3.amazonaws.com/redshift-downloads/amazon-redshift-rsql/1.0.7/AmazonRedshiftRsql-1.0.7.x86_64.rpm)
+ [RSQL 版本 1.0.6](https://s3.amazonaws.com/redshift-downloads/amazon-redshift-rsql/1.0.6/AmazonRedshiftRsql-1.0.6.x86_64.rpm)
+ [RSQL 版本 1.0.5](https://s3.amazonaws.com/redshift-downloads/amazon-redshift-rsql/1.0.5/AmazonRedshiftRsql-1.0.5-1.x86_64.rpm)
+ [RSQL 版本 1.0.4](https://s3.amazonaws.com/redshift-downloads/amazon-redshift-rsql/1.0.4/AmazonRedshiftRsql-1.0.4-1.x86_64.rpm)
+ [RSQL 版本 1.0.3](https://s3.amazonaws.com/redshift-downloads/amazon-redshift-rsql/1.0.3/AmazonRedshiftRsql-1.0.3-1.x86_64.rpm)
+ [RSQL 版本 1.0.1](https://s3.amazonaws.com/redshift-downloads/amazon-redshift-rsql/1.0.1/AmazonRedshiftRsql-1.0.1-1.x86_64.rpm)

**Mac OS 64 位 DMG/PKG**
+ [RSQL 版本 1.1.1](https://s3.amazonaws.com/redshift-downloads/amazon-redshift-rsql/1.1.1/AmazonRedshiftRsql-1.1.1.universal.pkg)
+ [RSQL 版本 1.1.0](https://s3.amazonaws.com/redshift-downloads/amazon-redshift-rsql/1.1.0/AmazonRedshiftRsql-1.1.0.universal.pkg)
+ [RSQL 版本 1.0.8](https://s3.amazonaws.com/redshift-downloads/amazon-redshift-rsql/1.0.8/AmazonRedshiftRsql-1.0.8.x86_64.dmg)
+ [RSQL 版本 1.0.7](https://s3.amazonaws.com/redshift-downloads/amazon-redshift-rsql/1.0.7/AmazonRedshiftRsql-1.0.7.x86_64.dmg)
+ [RSQL 版本 1.0.6](https://s3.amazonaws.com/redshift-downloads/amazon-redshift-rsql/1.0.6/AmazonRedshiftRsql-1.0.6.x86_64.dmg)
+ [RSQL 版本 1.0.5](https://s3.amazonaws.com/redshift-downloads/amazon-redshift-rsql/1.0.5/AmazonRedshiftRsql-1.0.5.dmg)
+ [RSQL 版本 1.0.4](https://s3.amazonaws.com/redshift-downloads/amazon-redshift-rsql/1.0.4/AmazonRedshiftRsql-1.0.4.dmg)
+ [RSQL 版本 1.0.3](https://s3.amazonaws.com/redshift-downloads/amazon-redshift-rsql/1.0.3/AmazonRedshiftRsql-1.0.3.dmg)
+ [RSQL 版本 1.0.1](https://s3.amazonaws.com/redshift-downloads/amazon-redshift-rsql/1.0.1/AmazonRedshiftRsql-1.0.1.dmg)

**Windows 64 位 MSI**
+ [RSQL 版本 1.1.1](https://s3.amazonaws.com/redshift-downloads/amazon-redshift-rsql/1.1.1/AmazonRedshiftRsql-1.1.1.x86_64.msi)
+ [RSQL 版本 1.1.0](https://s3.amazonaws.com/redshift-downloads/amazon-redshift-rsql/1.1.0/AmazonRedshiftRsql-1.1.0.x86_64.msi)
+ [RSQL 版本 1.0.8](https://s3.amazonaws.com/redshift-downloads/amazon-redshift-rsql/1.0.8/AmazonRedshiftRsql-1.0.8.x86_64.msi)
+ [RSQL 版本 1.0.7](https://s3.amazonaws.com/redshift-downloads/amazon-redshift-rsql/1.0.7/AmazonRedshiftRsql-1.0.7.x86_64.msi)
+ [RSQL 版本 1.0.6](https://s3.amazonaws.com/redshift-downloads/amazon-redshift-rsql/1.0.6/AmazonRedshiftRsql-1.0.6.x86_64.msi)
+ [RSQL 版本 1.0.5](https://s3.amazonaws.com/redshift-downloads/amazon-redshift-rsql/1.0.5/AmazonRedshiftRsql-1.0.5.msi)
+ [RSQL 版本 1.0.4](https://s3.amazonaws.com/redshift-downloads/amazon-redshift-rsql/1.0.4/AmazonRedshiftRsql-1.0.4.msi)
+ [RSQL 版本 1.0.3](https://s3.amazonaws.com/redshift-downloads/amazon-redshift-rsql/1.0.3/AmazonRedshiftRsql-1.0.3.msi)
+ [RSQL 版本 1.0.1](https://s3.amazonaws.com/redshift-downloads/amazon-redshift-rsql/1.0.1/AmazonRedshiftRsql-1.0.1.msi)

# 使用 Amazon Redshift RSQL 连接到集群
<a name="rsql-query-tool-starting-tool-connection"></a>

使用 Amazon Redshift，您可以连接到集群并使用 RSQL 与之交互。这是一个命令行工具，提供了一种安全的方式来查询数据、创建数据库对象和管理 Amazon Redshift 集群。以下各节将指导您完成使用 RSQL（带或不带数据来源名称（DSN））与集群建立连接的步骤。

## 在没有 DSN 的情况下连接
<a name="rsql-query-tool-starting-tool-connection-dsn-less-example"></a>

1. 在 Amazon Redshift 控制台上，选择要连接到的集群，然后记下端点、数据库和端口。

1. 在命令提示符下，使用命令行参数指定连接信息。

   ```
   rsql -h <endpoint> -U <username> -d <databasename> -p <port>
   ```

    在这里，以下内容适用：
   +  *<endpoint>* 是您在上一步中记录的**端点**。
   +  *<userid>* 是有权连接到集群的用户。
   +  *<databasename>* 是您在上一步中记录的**数据库名称**。
   +  *<port>* 是您在上一步中记录的**端口**。*<port>* 是一个可选参数。

   以下为示例。

   ```
   rsql -h testcluster.example.amazonaws.com -U user1 -d dev -p 5439
   ```

1.  在密码提示符处，输入 *<username>* 用户的密码。

   成功的连接响应如下所示。

   ```
   % rsql -h testcluster.example.com -d dev -U user1 -p 5349
   Password for user user1:
   DSN-less Connected
   DBMS Name: Amazon Redshift
   Driver Name: Amazon Redshift ODBC Driver
   Driver Version: 1.4.27.1000
   Rsql Version: 1.0.1
   Redshift Version: 1.0.29306
   Type "help" for help.
   
   (testcluster) user1@dev=#
   ```

要连接的命令在 Linux、Mac OS 和 Windows 上具有相同的参数。

## 在使用 DSN 的情况下连接
<a name="rsql-query-tool-starting-tool-connection-dsn-example"></a>

可以使用 DSN 将 RSQL 连接到 Amazon Redshift，以简化连接属性的整理方式。本主题包括 ODBC 驱动程序安装说明和 DSN 属性的描述。

### 使用带密码的 DSN 连接
<a name="rsql-query-tool-starting-tool-connection-dsn-example-password"></a>

下面显示使用密码的 DSN 连接配置的示例。对于 Mac OSX 而言，默认 `<path to driver>` 为 `/opt/amazon/redshift/lib/libamazonredshiftodbc.dylib`，对于 Linux 而言，则为 `/opt/amazon/redshiftodbc/lib/64/libamazonredshiftodbc64.so`。

```
[testuser]
Driver=/opt/amazon/redshiftodbc/lib/64/libamazonredshiftodbc64.so
SSLMode=verify-ca
Min_TLS=1.2
boolsaschar=0
Host=<server endpoint>
Port=<database port>
Database=<dbname>
UID=<username>
PWD=<password>
sslmode=prefer
```

连接成功后，输出结果如下。

```
% rsql -D testuser
DSN Connected
DBMS Name: Amazon Redshift
Driver Name: Amazon Redshift ODBC Driver
Driver Version: 1.4.27.1000
Rsql Version: 1.0.1
Redshift Version: 1.0.29306
Type "help" for help.

(testcluster) user1@dev=#
```

### 使用单点登录 DSN
<a name="rsql-query-tool-starting-tool-connection-dsn"></a>

您可以配置 DSN 以进行单点登录身份验证。下面显示使用 Okta 单点登录的 DSN 连接配置的示例。

```
[testokta]
Driver=<path to driver>
SSLMode=verify-ca
Min_TLS=1.2
boolsaschar=0
Host=<server endpoint>
clusterid=<cluster id>
region=<region name>
Database=<dbname>
locale=en-US
iam=1
plugin_name=<plugin name>
uid=<okta username>
pwd=<okta password>
idp_host=<idp endpoint>
app_id=<app id>
app_name=<app name>
preferred_role=<role arn>
```

成功连接的输出示例。

```
% rsql -D testokta 
DSN Connected
DBMS Name: Amazon Redshift
Driver Name: Amazon Redshift ODBC Driver
Driver Version: 1.4.27.1000
Rsql Version: 1.0.1
Redshift Version: 1.0.29306
Type "help" for help.

(testcluster) user1@dev=#
```

下面显示使用 Azure 单点登录的 DSN 连接配置的示例。

```
[testazure]
Driver=<path to driver>
SSLMode=verify-ca
Min_TLS=1.2
boolsaschar=0
Host=<server endpoint>
Port=<cluster port>
clusterid=<cluster id>
region=<region name>
Database=<dbname>
locale=en-us
iam=1
plugin_name=<plugin name>
uid=<azure username>
pwd=<azure password>
idp_tenant=<Azure idp tenant uuid>
client_id=<Azure idp client uuid>
client_secret=<Azure idp client secret>
```

### 将 DSN 连接与 IAM 配置文件结合使用
<a name="rsql-query-tool-starting-tool-connection-dsn-iam"></a>

您可以使用配置的 IAM 配置文件连接到 Amazon Redshift。IAM 配置文件必须具有调用 `GetClusterCredentials` 的权限。以下示例演示了要使用的 DSN 属性。仅当 `Host` 不是 Amazon 提供的端点（如 `examplecluster.abc123xyz789.us-west-2.redshift.amazonaws.com`）时，才需要 `ClusterID` 和 `Region` 参数。

```
[testiam]
Driver=Default
Host=testcluster.example.com
Database=dev
DbUser=testuser
ClusterID=rsqltestcluster
Region=us-east-1
IAM=1
Profile=default
```

`Profile` 密钥的值是您从 AWS CLI 凭证中选择的命名配置文件。此示例显示名为 `default` 的配置文件的凭证。

```
$ cat .aws/credentials
[default]
aws_access_key_id = ASIAIOSFODNN7EXAMPLE 
aws_secret_access_key = wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
```

下面显示的是连接响应。

```
$ rsql -D testiam
DSN Connected
DBMS Name: Amazon Redshift
Driver Name: Amazon Redshift ODBC Driver
Driver Version: 1.4.27.1000
Rsql Version: 1.0.1
Redshift Version: 1.0.29306
Type "help" for help.

(testcluster) testuser@dev=>
```

### 将 DSN 连接与实例配置文件结合使用
<a name="rsql-query-tool-starting-tool-connection-dsn-instance"></a>

您可以使用 Amazon EC2 实例配置文件连接到 Amazon Redshift。实例配置文件必须具有调用 `GetClusterCredentials` 的权限。有关要使用的 DSN 属性，请参阅下面的示例。仅当 `Host` 不是 Amazon 提供的端点（如 `examplecluster.abc123xyz789.us-west-2.redshift.amazonaws.com`）时，才需要 `ClusterID` 和 `Region` 参数。

```
[testinstanceprofile]
Driver=Default
Host=testcluster.example.com
Database=dev
DbUser=testuser
ClusterID=rsqltestcluster
Region=us-east-1
IAM=1
Instanceprofile=1
```

下面显示的是连接响应。

```
$ rsql -D testinstanceprofile
DSN Connected
DBMS Name: Amazon Redshift
Driver Name: Amazon Redshift ODBC Driver
Driver Version: 1.4.27.1000
Rsql Version: 1.0.1
Redshift Version: 1.0.29306
Type "help" for help.

(testcluster) testuser@dev=>
```

### 将 DSN 连接与默认凭证提供程序链结合使用
<a name="rsql-query-tool-starting-tool-connection-dsn-provider-chain"></a>

要使用默认凭证提供程序链进行连接，请仅指定 IAM 属性，Amazon Redshift RSQL 将尝试按照适用于 Java 的 AWS SDK 中[使用 AWS 凭证](https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/credentials.html)所述的顺序获取凭证。链中必须至少一个提供程序具有 `GetClusterCredentials` 权限。例如，这对于从 ECS 容器进行连接非常有用。

```
[iamcredentials]
Driver=Default
Host=testcluster.example.com
Database=dev
DbUser=testuser
ClusterID=rsqltestcluster
Region=us-east-1
IAM=1
```

# Amazon Redshift RSQL 元命令
<a name="rsql-query-tool-commands"></a>

Amazon Redshift RSQL 元命令返回有关数据库或特定数据库对象的信息性记录。结果可以包括各种列和元数据。其他命令会执行特定操作。这些命令的前面都有反斜杠。

## \$1d[S\$1]
<a name="rsql-query-tool-describe-d"></a>

 列出本地用户创建的表、常规视图、后期绑定视图和实体化视图。`\dS ` 还列出了表和视图，如 `\d`，但系统对象包含在返回的记录中。`+` 为所有列出的对象生成额外的元数据列 `description`。下面显示的是作为命令返回的示例记录。

```
List of relations
 schema |   name    | type  |  owner  
--------+-----------+-------+---------
 public | category  | table | awsuser
 public | date      | table | awsuser
 public | event     | table | awsuser
 public | listing   | table | awsuser
 public | sales     | table | awsuser
 public | users     | table | awsuser
 public | venue     | table | awsuser
(7 rows)
```

## \$1d[S\$1] NAME
<a name="rsql-query-tool-describe-s-plus-named"></a>

描述表、视图或索引。包括列名称和类型。它还提供了 diststyle、备份配置、创建日期（2018 年 10 月之后创建的表）和约束。例如，`\dS+ sample` 返回对象属性。附加 `S+` 会导致返回的记录中包含其它列。

```
Table "public.sample"
 Column |            Type             |   Collation    | Nullable | Default Value | Encoding  | DistKey | SortKey
--------+-----------------------------+----------------+----------+---------------+-----------+---------+---------
 col1   | smallint                    |                | NO       |               | none      | t       | 1
 col2   | character(100)              | case_sensitive | YES      |               | none      | f       | 2
 col3   | character varying(100)      | case_sensitive | YES      |               | text32k   | f       | 3
 col4   | timestamp without time zone |                | YES      |               | runlength | f       | 0
 col5   | super                       |                | YES      |               | zstd      | f       | 0
 col6   | bigint                      |                | YES      |               | az64      | f       | 0

Diststyle: KEY
Backup: YES
Created: 2021-07-20 19:47:27.997045
Unique Constraints:
    "sample_pkey" PRIMARY KEY (col1)
    "sample_col2_key" UNIQUE (col2)
Foreign-key constraints:
    "sample_col2_fkey" FOREIGN KEY (col2) REFERENCES lineitem(l_orderkey)
```

表的分布样式或 *Diststyle* 可以是 KEY、AUTO、EVEN 或 ALL。

*备份*指示在拍摄快照时是否备份了表。有效值为 `YES` 或 `NO`。

*已创建*是创建表的时间的时间戳。创建日期不适用于 2018 年 11 月之前创建的 Amazon Redshift 表。在此日期之前创建的表显示 n/a（不可用）。

*独特约束*列出了表中的唯一的主键约束。

*外键约束*列出了表中的外键越塾。

## \$1dC[\$1] [PATTERN]
<a name="rsql-query-tool-describe-dc"></a>

列出转换。包括源类型、目标类型以及转换是否为隐式。

以下显示来自 `\dC+` 的结果子集：

```
List of casts
         source type         |         target type         |      function       |   implicit?   | description 
-----------------------------+-----------------------------+---------------------+---------------+-------------
 "char"                      | character                   | bpchar              | in assignment | 
 "char"                      | character varying           | text                | in assignment | 
 "char"                      | integer                     | int4                | no            | 
 "char"                      | text                        | text                | yes           | 
 "path"                      | point                       | point               | no            | 
 "path"                      | polygon                     | polygon             | in assignment | 
 abstime                     | date                        | date                | in assignment | 
 abstime                     | integer                     | (binary coercible)  | no            | 
 abstime                     | time without time zone      | time                | in assignment | 
 abstime                     | timestamp with time zone    | timestamptz         | yes           | 
 abstime                     | timestamp without time zone | timestamp           | yes           | 
 bigint                      | bit                         | bit                 | no            | 
 bigint                      | boolean                     | bool                | yes           | 
 bigint                      | character                   | bpchar              | in assignment | 
 bigint                      | character varying           | text                | in assignment | 
 bigint                      | double precision            | float8              | yes           | 
 bigint                      | integer                     | int4                | in assignment | 
 bigint                      | numeric                     | numeric             | yes           | 
 bigint                      | oid                         | oid                 | yes           | 
 bigint                      | real                        | float4              | yes           | 
 bigint                      | regclass                    | oid                 | yes           | 
 bigint                      | regoper                     | oid                 | yes           | 
 bigint                      | regoperator                 | oid                 | yes           | 
 bigint                      | regproc                     | oid                 | yes           | 
 bigint                      | regprocedure                | oid                 | yes           | 
 bigint                      | regtype                     | oid                 | yes           | 
 bigint                      | smallint                    | int2                | in assignment | 
 bigint                      | super                       | int8_partiql        | in assignment |
```

## \$1dd[S] [PATTERN]
<a name="rsql-query-tool-describe-dds"></a>

显示在别处未显示的对象描述。

## \$1de
<a name="rsql-query-tool-describe-de"></a>

列出外部表。这包括 AWS Glue Data Catalog 中的表、Hive Metastore 和来自 Amazon RDS/Aurora MySQL、Amazon RDS/Aurora PostgreSQL 和 Amazon Redshift 数据共享表的联合表。

## \$1de NAME
<a name="rsql-query-tool-describe-de-name"></a>

描述外部表。

以下示例显示 AWS Glue 外部表。

```
# \de spectrum.lineitem
                            Glue External table "spectrum.lineitem"
     Column      | External Type | Redshift Type | Position | Partition Key | Nullable
-----------------+---------------+---------------+----------+---------------+----------
 l_orderkey      | bigint        | bigint        | 1        | 0             |
 l_partkey       | bigint        | bigint        | 2        | 0             |
 l_suppkey       | int           | int           | 3        | 0             |
 l_linenumber    | int           | int           | 4        | 0             |
 l_quantity      | decimal(12,2) | decimal(12,2) | 5        | 0             |
 l_extendedprice | decimal(12,2) | decimal(12,2) | 6        | 0             |
 l_discount      | decimal(12,2) | decimal(12,2) | 7        | 0             |
 l_tax           | decimal(12,2) | decimal(12,2) | 8        | 0             |
 l_returnflag    | char(1)       | char(1)       | 9        | 0             |
 l_linestatus    | char(1)       | char(1)       | 10       | 0             |
 l_shipdate      | date          | date          | 11       | 0             |
 l_commitdate    | date          | date          | 12       | 0             |
 l_receiptdate   | date          | date          | 13       | 0             |
 l_shipinstruct  | char(25)      | char(25)      | 14       | 0             |
 l_shipmode      | char(10)      | char(10)      | 15       | 0             |
 l_comment       | varchar(44)   | varchar(44)   | 16       | 0             |

Location: s3://redshiftbucket/kfhose2019/12/31
Input_format: org.apache.hadoop.mapred.TextInputFormat
Output_format: org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat
Serialization_lib: org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe
Serde_parameters: {"field.delim":"|","serialization.format":"|"}
Parameters: {"EXTERNAL":"TRUE","numRows":"178196721475","transient_lastDdlTime":"1577771873"}
```

Hive Metastore 表。

```
# \de emr.lineitem
                     Hive Metastore External Table "emr.lineitem"
     Column      | External Type | Redshift Type | Position | Partition Key | Nullable
-----------------+---------------+---------------+----------+---------------+----------
 l_orderkey      | bigint        | bigint        | 1        | 0             |
 l_partkey       | bigint        | bigint        | 2        | 0             |
 l_suppkey       | int           | int           | 3        | 0             |
 l_linenumber    | int           | int           | 4        | 0             |
 l_quantity      | decimal(12,2) | decimal(12,2) | 5        | 0             |
 l_extendedprice | decimal(12,2) | decimal(12,2) | 6        | 0             |
 l_discount      | decimal(12,2) | decimal(12,2) | 7        | 0             |
 l_tax           | decimal(12,2) | decimal(12,2) | 8        | 0             |
 l_returnflag    | char(1)       | char(1)       | 9        | 0             |
 l_linestatus    | char(1)       | char(1)       | 10       | 0             |
 l_commitdate    | date          | date          | 11       | 0             |
 l_receiptdate   | date          | date          | 12       | 0             |
 l_shipinstruct  | char(25)      | char(25)      | 13       | 0             |
 l_shipmode      | char(10)      | char(10)      | 14       | 0             |
 l_comment       | varchar(44)   | varchar(44)   | 15       | 0             |
 l_shipdate      | date          | date          | 16       | 1             |

Location: s3://redshiftbucket/cetas
Input_format: org.apache.hadoop.hive.ql.io.parquet.MapredParquetInputFormat
Output_format: org.apache.hadoop.hive.ql.io.parquet.MapredParquetOutputFormat
Serialization_lib: org.apache.hadoop.hive.ql.io.parquet.serde.ParquetHiveSerDe
Serde_parameters: {"serialization.format":"1"}
Parameters: {"EXTERNAL":"TRUE", "numRows":"4307207", "transient_lastDdlTime":"1626990007"}
```

PostgreSQL 外部表。

```
# \de pgrsql.alltypes
                                Postgres Federated Table "pgrsql.alltypes"
 Column |        External Type        |        Redshift Type        | Position | Partition Key | Nullable
--------+-----------------------------+-----------------------------+----------+---------------+----------
 col1   | bigint                      | bigint                      | 1        | 0             |
 col2   | bigint                      | bigint                      | 2        | 0             |
 col5   | boolean                     | boolean                     | 3        | 0             |
 col6   | box                         | varchar(65535)              | 4        | 0             |
 col7   | bytea                       | varchar(65535)              | 5        | 0             |
 col8   | character(10)               | character(10)               | 6        | 0             |
 col9   | character varying(10)       | character varying(10)       | 7        | 0             |
 col10  | cidr                        | varchar(65535)              | 8        | 0             |
 col11  | circle                      | varchar(65535)              | 9        | 0             |
 col12  | date                        | date                        | 10       | 0             |
 col13  | double precision            | double precision            | 11       | 0             |
 col14  | inet                        | varchar(65535)              | 12       | 0             |
 col15  | integer                     | integer                     | 13       | 0             |
 col16  | interval                    | varchar(65535)              | 14       | 0             |
 col17  | json                        | varchar(65535)              | 15       | 0             |
 col18  | jsonb                       | varchar(65535)              | 16       | 0             |
 col19  | line                        | varchar(65535)              | 17       | 0             |
 col20  | lseg                        | varchar(65535)              | 18       | 0             |
 col21  | macaddr                     | varchar(65535)              | 19       | 0             |
 col22  | macaddr8                    | varchar(65535)              | 20       | 0             |
 col23  | money                       | varchar(65535)              | 21       | 0             |
 col24  | numeric                     | numeric(38,20)              | 22       | 0             |
 col25  | path                        | varchar(65535)              | 23       | 0             |
 col26  | pg_lsn                      | varchar(65535)              | 24       | 0             |
 col28  | point                       | varchar(65535)              | 25       | 0             |
 col29  | polygon                     | varchar(65535)              | 26       | 0             |
 col30  | real                        | real                        | 27       | 0             |
 col31  | smallint                    | smallint                    | 28       | 0             |
 col32  | smallint                    | smallint                    | 29       | 0             |
 col33  | integer                     | integer                     | 30       | 0             |
 col34  | text                        | varchar(65535)              | 31       | 0             |
 col35  | time without time zone      | varchar(65535)              | 32       | 0             |
 col36  | time with time zone         | varchar(65535)              | 33       | 0             |
 col37  | timestamp without time zone | timestamp without time zone | 34       | 0             |
 col38  | timestamp with time zone    | timestamp with time zone    | 35       | 0             |
 col39  | tsquery                     | varchar(65535)              | 36       | 0             |
 col40  | tsvector                    | varchar(65535)              | 37       | 0             |
 col41  | txid_snapshot               | varchar(65535)              | 38       | 0             |
 col42  | uuid                        | varchar(65535)              | 39       | 0             |
 col43  | xml                         | varchar(65535)              | 40       | 0             |
```

## \$1df[anptw][S\$1] [PATTERN]
<a name="rsql-query-tool-df"></a>

 列出各种类型的函数。例如，命令 `\df` 返回函数列表。结果包括名称、返回的数据类型、访问权限和其它元数据等属性。函数类型可以包括触发器、存储过程、窗口函数和其它类型。当您将 `S+` 附加到命令（例如 `\dfantS+`）时，会包含其它元数据列，例如 `owner`、`security` 和 `access privileges`。

## \$1dL[S\$1] [PATTERN]
<a name="rsql-query-tool-describe-dl"></a>

 列出与数据库关联的过程语言的数据。信息包括名称（例如 plpgsql）和其它元数据，其中包括名称是否受信任、访问权限和描述。例如，示例调用是 `\dLS+`，它列出了语言及其属性。当您将 `S+` 附加到命令时，会包含其它元数据列，例如 `call handler` 和 `access privileges`。

示例结果：

```
List of languages
   name    | trusted | internal language |      call handler       |                         validator                          | access privileges |          description           
-----------+---------+-------------------+-------------------------+------------------------------------------------------------+-------------------+--------------------------------
 c         | f       | t                 | -                       | fmgr_c_validator(oid)                                      |                   | Dynamically-loaded C functions
 exfunc    | f       | f                 | exfunc_call_handler()   | -                                                          | rdsdb=U/rdsdb     | 
 internal  | f       | t                 | -                       | fmgr_internal_validator(oid)                               |                   | Built-in functions
 mlfunc    | f       | f                 | mlfunc_call_handler()   | -                                                          | rdsdb=U/rdsdb     | 
 plpgsql   | t       | f                 | plpgsql_call_handler()  | plpgsql_validator(oid)                                     |                   | 
 plpythonu | f       | f                 | plpython_call_handler() | plpython_compiler(cstring,cstring,cstring,cstring,cstring) | rdsdb=U/rdsdb     | 
 sql       | t       | t                 | -                       | fmgr_sql_validator(oid)                                    | =U/rdsdb          | SQL-language functions
```

## \$1dm[S\$1] [PATTERN]
<a name="rsql-query-tool-describe-dm"></a>

 列出实体化视图。例如，`\dmS+` 列出了实体化视图及其属性。当您将 `S+` 附加到命令时，会包含其它元数据列。

## \$1dn[S\$1] [PATTERN]
<a name="rsql-query-tool-describe-dn"></a>

 列出架构。当您将 `S+` 附加到命令（例如 `\dnS+`）时，会包含其它元数据列，例如 `description` 和 `access privileges`。

## \$1dp [PATTERN]
<a name="rsql-query-tool-describe-dp"></a>

 列出表、视图和序列访问权限。

## \$1dt[S\$1] [PATTERN]
<a name="rsql-query-tool-describe-dt"></a>

 列出表 当您将 `S+` 附加到命令（例如 `\dtS+`）时，会包含其它元数据列，例如本例中的 `description`。

## \$1du
<a name="rsql-query-tool-describe-du"></a>

 列出数据库的用户。包括他们的姓名和角色，例如超级用户和属性。

## \$1dv[S\$1] [PATTERN]
<a name="rsql-query-tool-describe-dv"></a>

 列出视图。包括架构、类型和拥有者数据。当您将 `S+` 附加到命令（例如 `\dvS+`）时，会包含其它元数据列。

## \$1H
<a name="rsql-query-tool-describe-h"></a>

 打开 HTML 输出。这对于快速返回格式化的结果非常有用。例如，`select * from sales; \H` 以 HTML 格式返回销售表中的结果。要切换回表格结果，请使用 `\q`，或者无提示。

## \$1i
<a name="rsql-query-tool-describe-i"></a>

 从文件中运行命令。例如，假设您的工作目录中有 rsql\$1steps.sql，以下将运行文件中的命令：`\i rsql_steps.sql`。

## \$1l[\$1] [PATTERN]
<a name="rsql-query-tool-describe-l"></a>

 列出数据库。包括所有者、编码和其它信息。

## \$1q
<a name="rsql-query-tool-describe-q"></a>

 退出，或者 `\q` 命令，注销数据库会话并退出 RSQL。

## \$1sv[\$1] VIEWNAME
<a name="rsql-query-tool-describe-sv-name"></a>

 显示视图的定义。

## \$1timing
<a name="rsql-query-tool-describe-timing"></a>

 例如，显示查询的运行时间。

## \$1z [PATTERN]
<a name="rsql-query-tool-describe-z"></a>

 输出与\$1 dp 相同。

## \$1?
<a name="rsql-query-tool-help"></a>

 显示帮助信息。可选的参数指定要解释的项目。

## \$1EXIT
<a name="rsql-query-tool-flow-control-exit"></a>

 注销所有数据库会话并退出 Amazon Redshift RSQL。此外，您可以指定可选的退出代码。例如，`\EXIT 15` 将退出 Amazon Redshift RSQL 终端并返回退出代码 15。

以下示例显示来自连接的输出并从 RSQL 退出。

```
% rsql -D testuser
DSN Connected
DBMS Name: Amazon Redshift
Driver Name: Amazon Redshift ODBC Driver
Driver Version: 1.4.34.1000
Rsql Version: 1.0.1
Redshift Version: 1.0.29306 
Type "help" for help.

(testcluster) user1@dev=# \exit 15

% echo $?
15
```

## \$1EXPORT
<a name="rsql-query-tool-export"></a>

 指定导出文件的名称，RSQL 将该文件用于存储后续 SQL SELECT 语句返回的数据库信息。

export\$101.sql

```
\export report file='E:\\accounts.out'
\rset rformat off
\rset width 1500
\rset heading "General Title"
\rset titledashes on
select * from td_dwh.accounts;
\export reset
```

控制台输出

```
Rformat is off.
Target width is 1500.
Heading is set to: General Title
Titledashes is on.
(exported 40 rows)
```

## \$1LOGON
<a name="rsql-query-tool-flow-control-logon"></a>

 连接到数据库。您可以使用位置语法指定连接参数或将其指定作为连接字符串。

命令语法如下所示：`\logon {[DBNAME|- USERNAME|- HOST|- PORT|- [PASSWORD]] | conninfo}`

`DBNAME` 是要连接的数据库的名称。`USERNAME` 是连接的用户名。默认 `HOST` 为 `localhost`。默认 `PORT` 为 `5439`。

当在 `\LOGON` 命令中指定主机名时，它将成为其它 `\LOGON` 命令的默认主机名。要更改默认主机名，请在附加 `\LOGON` 命令中指定新的 `HOST`。

`user1` 的 `\LOGON` 命令输出示例如下。

```
(testcluster) user1@redshiftdb=# \logon dev
DBMS Name: Amazon Redshift
Driver Name: Amazon Redshift ODBC Driver
Driver Version: 1.4.27.1000
Rsql Version: 1.0.1
You are now connected to database "dev" as user "user1".
(testcluster) user1@dev=#
```

*user2* 的示例输出。

```
(testcluster) user1@dev=# \logon dev user2 testcluster2.example.com
Password for user user2: 
DBMS Name: Amazon Redshift
Driver Name: Amazon Redshift ODBC Driver
Driver Version: 1.4.27.1000
Rsql Version: 1.0.1
You are now connected to database "dev" as user "user2" on host "testcluster2.example.com" at port "5439".
(testcluster2) user2@dev=#
```

## \$1REMARK
<a name="rsql-query-tool-flow-control-remark"></a>

 `\echo` 命令的扩展。`\REMARK` 将指定的字符串打印到输出流。`\REMARK ` 通过添加在单独的行上中断输出的能力来扩展 `\echo`。

以下示例显示了命令的输出。

```
(testcluster) user1@dev=# \remark 'hello//world'
hello
world
```

## \$1RSET
<a name="rsql-query-tool-rset"></a>

该 `\rset` 命令将设置命令参数和变量。`\rset` 还具有交互式模式和批处理模式。它不支持 bash 选项（例如 *-x*）或参数（例如 *--<arg>*）。

它设置如下所示的变量：
+ ERRORLEVEL
+ HEADING 和 RTITLE
+ RFORMAT
+ MAXERROR
+ TITLEDASHES
+ WIDTH

以下示例指定一个标题。

```
\rset heading "Winter Sales Report"
```

有关如何使用 `\rset` 的更多示例，您可以在 [Amazon Redshift RSQL 变量](rsql-query-tool-variables.md) 主题中查找示例。

## \$1RUN
<a name="rsql-query-tool-flow-control-run"></a>

 运行包含在指定文件中的 Amazon Redshift RSQL 脚本。`\RUN` 通过添加一个选项来跳过文件中的标题行以扩展 `\i` 命令。

如果文件名包含逗号、分号或空格，请用单引号将其括起来。此外，如果文本在文件名后面，请将其括在引号中。在 UNIX 中，文件名区分大小写。在 Windows 中，文件名不区分大小写。

以下示例显示了命令的输出。

```
(testcluster) user1@dev=# \! cat test.sql
select count(*) as lineitem_cnt from lineitem;
select count(*) as customer_cnt from customer;
select count(*) as orders_cnt from orders;



(testcluster) user1@dev=# \run file=test.sql
 lineitem_cnt
--------------
      4307207
(1 row)

 customer_cnt
--------------
     37796166
(1 row)

 orders_cnt
------------
          0
(1 row)


(testcluster) user1@dev=# \run file=test.sql skip=2
2 records skipped in RUN file.
 orders_cnt
------------
          0
(1 row)
```

## \$1OS
<a name="rsql-query-tool-flow-control-os"></a>

 `\!` 命令的别名。`\OS` 运行作为参数传递的操作系统命令。命令运行后，控制将返回到 Amazon Redshift RSQL。例如，您可以运行以下命令以打印当前系统日期时间并返回到 RSQL 终端：`\os date`。

```
(testcluster) user1@dev=# \os date
Tue Sep 7 20:47:54 UTC 2021
```

## \$1GOTO
<a name="rsql-query-tool-flow-control-goto"></a>

 适用于 Amazon Redshift RSQL 的新命令。`\GOTO` 跳过所有干预命令并在指定的 `\LABEL` 继续处理。`\LABEL` 必须是前向引用。您不能跳转到词汇上位于 `\GOTO` 之前的 `\LABEL`。

下面显示了示例输出。

```
(testcluster) user1@dev=# \! cat test.sql
select count(*) as cnt from lineitem \gset
select :cnt as cnt;
\if :cnt > 100
    \goto LABELB
\endif

\label LABELA
\remark 'this is label LABELA'
\label LABELB
\remark 'this is label LABELB'


(testcluster) user1@dev=# \i test.sql
   cnt
---------
 4307207
(1 row)

\label LABELA ignored
\label LABELB processed
this is label LABELB
```

## \$1LABEL
<a name="rsql-query-tool-flow-control-label"></a>

 适用于 Amazon Redshift RSQL 的新命令。`\LABEL` 建立运行程序的入口点，作为 `\GOTO` 命令的目标。

以下显示了命令的输出。

```
(testcluster) user1@dev=# \! cat test.sql
select count(*) from lineitem limit 5;
\goto LABELB
\remark "this step was skipped by goto label";
\label LABELA
\remark 'this is label LABELA'
\label LABELB
\remark 'this is label LABELB'



(testcluster) user1@dev=# \i testgoto.sql
  count
 4307193
(1 row)

\label LABELA ignored
\label LABELB processed
this is label LABELB
```

## \$1IF (\$1ELSEIF, \$1ELSE, \$1ENDIF)
<a name="rsql-query-tool-flow-control-if"></a>

 `\IF` 和相关命令有条件地运行部分输入脚本。PSQL `\if`（`\elif`、`\else`、`\endif`）命令的扩展。`\IF` 和 `\ELSEIF` 支持布尔表达式，包括 `AND`、`OR` 和 `NOT` 条件。

以下显示了命令的示例输出。

```
(testcluster) user1@dev=# \! cat test.sql
SELECT query FROM stv_inflight LIMIT 1 \gset
select :query as query;
\if :query > 1000000
    \remark 'Query id is greater than 1000000'
\elseif :query = 1000000
    \remark 'Query id is equal than 1000000'
\else
    \remark 'Query id is less than 1000000'
\endif


(testcluster) user1@dev=# \i test.sql 
 query
--------
 994803
(1 row)
 
Query id is less than 1000000
```

在您的分支逻辑中使用 `ERRORCODE`。

```
\if :'ERRORCODE' = '00000'
    \remark 'The statement was executed without error'
\else
    \remark :LAST_ERROR_MESSAGE
\endif
```

在 `\IF` 块内使用 `\GOTO` 以控制代码的运行方式。

# Amazon Redshift RSQL 变量
<a name="rsql-query-tool-variables"></a>

 有些关键字在 RSQL 中充当变量。您可以将每个值设置为特定值，也可以重新设置值。大多数值都由 `\rset` 设置，它具有交互式模式和批处理模式。命令可以用小写或大写定义。

## ACTIVITYCOUNT
<a name="rsql-query-tool-activitycount"></a>

 指示受上次提交的请求影响的行数。对于数据返回请求，这是从数据库返回到 RSQL 的行数。该值为 0 或正整数。最大值为 18,446,744,073,709,551,615。

 经过特殊处理的变量 `ACTIVITYCOUNT` 类似于变量 `ROW_COUNT`。但是，在命令完成时，`ROW_COUNT` 不会向客户端应用程序报告受影响的 `SELECT`、`COPY` 或 `UNLOAD` 行数。而 `ACTIVITYCOUNT` 会报告相关行数。

activitycount\$101.sql：

```
select viewname, schemaname
from pg_views
where schemaname = 'not_existing_schema';
\if :ACTIVITYCOUNT = 0
\remark 'views do not exist'
\endif
```

控制台输出：

```
viewname | schemaname
----------+------------
(0 rows)

views do not exist
```

## ERRORLEVEL
<a name="rsql-query-tool-describe-rset-errorlevel"></a>

为错误分配严重性级别。使用严重性级别来确定适当操作。如果尚未使用 `ERRORLEVEL` 命令，那么默认情况下，它的值为 `ON`。

errorlevel\$101.sql：

```
\rset errorlevel 42P01 severity 0

select * from tbl;

select 1 as col;

\echo exit
\quit
```

控制台输出：

```
Errorlevel is on.
rsql: ERROR: relation "tbl" does not exist
(1 row)

col
1

exit
```

## HEADING 和 RTITLE
<a name="rsql-query-tool-describe-rset-heading-rtitle"></a>

允许用户指定显示在报告顶部的标题。使用 `RSET RTITLE` 命令指定的标题会自动包含客户端电脑的当前系统日期。

rset\$1heading\$1rtitle\$102.rsql 内容：

```
\remark Starting...
\rset rtitle "Marketing Department||Confidential//Third Quarter//Chicago"
\rset width 70
\rset rformat on
select * from rsql_test.tbl_currency order by id limit 2;
\exit
\remark Finishing...
```

控制台输出：

```
Starting...
Rtitle is set to: &DATE||Marketing Department||Confidential//Third Quarter//Chicago (Changes will take effect after RFORMAT is
switched ON)
Target width is 70.
Rformat is on.
09/11/20       Marketing       Department Confidential
                  Third Quarter
                     Chicago
id  | bankid  | name |      start_date
100 |       1 | USD | 2020-09-11 10:51:39.106905
110 |       1 | EUR | 2020-09-11 10:51:39.106905
(2 rows)

Press any key to continue . . .
```

## MAXERROR
<a name="rsql-query-tool-describe-rset-maxerror"></a>

指定 RSQL 终止任务处理的最大错误严重性级别。在完成每个作业或任务后，返回代码是 RSQL 返回到客户端操作系统的整数值。返回代码的值表示作业或任务的完成状态。如果脚本包含生成错误严重性级别大于指定 `maxerror` 值的语句，RSQL 将立即退出。因此，要将 RSQL 退出的错误严重性级别设为 8，请使用 `RSET MAXERROR 7`。

maxerror\$101.sql 内容：

```
\rset maxerror 0
                        
select 1 as col;

\quit
```

控制台输出：

```
Maxerror is default.
(1 row)

col
1
```

## RFORMAT
<a name="rsql-query-tool-describe-rset-heading-rformat"></a>

允许用户指定是否应用格式化命令的设置。

rset\$1rformat.rsql 内容：

```
\remark Starting...
\pset border 2
\pset format wrapped
\pset expanded on
\pset title 'Great Title'
select * from rsql_test.tbl_long where id = 500;
\rset rformat
select * from rsql_test.tbl_long where id = 500;
\rset rformat off
select * from rsql_test.tbl_long where id = 500;
\rset rformat on
select * from rsql_test.tbl_long where id = 500;
\exit
\remark Finishing...
```

控制台输出：

```
Starting...
Border style is 2. (Changes will take effect after RFORMAT is switched ON)
Output format is wrapped. (Changes will take effect after RFORMAT is switched ON)
Expanded display is on. (Changes will take effect after RFORMAT is switched ON)
Title is "Great Title". (Changes will take effect after RFORMAT is switched ON)
id  |                                                             long_string
500 | In general, the higher the number the more borders and lines the tables will have, but details depend on the particular
format.
(1 row)

Rformat is on.
Great Title
+-[ RECORD 1 ]+----------------------------------------------------------------------------------------------------------------------
-----------+
| id           | 500
|
| long_string | In general, the higher the number the more borders and lines the tables will have, but details depend on the
particular format. |
+-------------+----------------------------------------------------------------------------------------------------------------------
-----------+

Rformat is off.
id  |                                                             long_string
500 | In general, the higher the number the more borders and lines the tables will have, but details depend on the particular format.
(1 row)

Rformat is on.
Great Title
+-[ RECORD 1 ]+----------------------------------------------------------------------------------------------------------------------
-----------+
| id           | 500
|
| long_string | In general, the higher the number the more borders and lines the tables will have, but details depend on the
particular format. |
+-------------+----------------------------------------------------------------------------------------------------------------------
-----------+
Press any key to continue . . .
```

## ROW\$1COUNT
<a name="rsql-query-tool-describe-rset-row_count"></a>

获取受以前查询影响的记录数。它通常用于检查结果，如以下代码片段所示：

```
SET result = ROW_COUNT;

IF result = 0
...
```

## TITLEDASHES
<a name="rsql-query-tool-describe-rset-heading-titledashes"></a>

使用此控件，用户可以指定是否要在为 SQL 语句返回的列数据的上方打印一行破折号字符。

示例：

```
\rset titledashes on
select dept_no, emp_no, salary from rsql_test.EMPLOYEE
where dept_no = 100;
\rset titledashes off
select dept_no, emp_no, salary from rsql_test.EMPLOYEE
where dept_no = 100;
```

控制台输出：

```
dept_no      emp_no          salary
----------- ----------- --------------------
100         1000346        1300.00
100         1000245        5000.00
100         1000262        2450.00

dept_no     emp_no         salary
100         1000346        1300.00
100         1000245        5000.00
100         1000262        2450.00
```

## WIDTH
<a name="rsql-query-tool-describe-rset-heading-width"></a>

将输出格式设置为换行并指定报告中每行的目标宽度。如果没有参数，它将返回格式和目标宽度的当前设置。

rset\$1width\$101.rsql 内容：

```
\echo Starting...
\rset width
\rset width 50
\rset width
\quit
\echo Finishing...
```

控制台输出：

```
Starting...
Target width is 75.
Target width is 50.
Target width is 50.
Press any key to continue . . .
```

使用参数的示例：

```
\echo Starting...
\rset rformat on
\pset format wrapped
select * from rsql_test.tbl_long where id = 500;
\rset width 50
select * from rsql_test.tbl_long where id = 500;
\quit
\echo Finishing...
```

控制台输出：

```
Starting...
Rformat is on.
Output format is wrapped.
id  |                                          long_string
500 | In general, the higher the number the more borders and lines the ta.
    |.bles will have, but details depend on the particular format.
(1 row)

Target width is 50.
id  |                                          long_string
500 | In general, the higher the number the more.
    |. borders and lines the tables will have, b.
    |.ut details depend on the particular format.
    |..
(1 row)
Press any key to continue . . .
```

# Amazon Redshift RSQL 错误代码
<a name="rsql-query-tool-error-codes"></a>

成功消息、警告和异常：

[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/redshift/latest/mgmt/rsql-query-tool-error-codes.html)

数据异常：

[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/redshift/latest/mgmt/rsql-query-tool-error-codes.html)

违反完整性约束：

[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/redshift/latest/mgmt/rsql-query-tool-error-codes.html)

# Amazon Redshift RSQL 环境变量
<a name="rsql-query-tool-environment-variables"></a>

 Amazon Redshift RSQL 可以使用环境变量来选择默认参数值。

## RSPASSWORD
<a name="rsql-query-tool-rspassword"></a>

**重要**  
出于安全原因，我们不建议使用此环境变量，因为有些操作系统允许非管理用户查看进程环境变量。

 为 Amazon Redshift RSQL 设置连接到 Amazon Redshift 时要使用的密码。此环境变量需要 Amazon Redshift RSQL 1.0.4 及更高版本。

 如果设置了 RSPASSWORD，RSQL 会优先考虑它。如果未设置 RSPASSWORD 并且您使用 DSN 进行连接，则 RSQL 将从 DSN 文件的参数中获取密码。最后，如果未设置 RSPASSWORD 且您没有使用 DSN，则 RSQL 会在尝试连接后提供密码提示。

下面为设置 RSPASSWORD 的示例：

```
export RSPASSWORD=TestPassw0rd
```