

 Amazon Redshift 將不再支援從修補程式 198 開始建立新的 Python UDFs。現有 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 中繼存放區中外部資料表的屬性或屬性、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 或 Microsoft 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>

請依照下列步驟安裝 RSQL for Mac OSX。

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. 將 `DYLD_LIBRARY_PATH` 設定為 libodbc.dylib 的位置 (如果它不在 `/usr/local/lib` 的話)。

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

1. 按兩下 pkg 檔案來執行安裝程式。

1. 依照安裝程式中的步驟完成安裝。同意授權合約中的條款。

## 安裝適用於 Windows 的 RSQL
<a name="rsql-query-tool-windows-install"></a>

請依照下列步驟安裝 RSQL for Windows。

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)*

錯誤修正
+ 修正 RSQL 在使用 -c 旗標時錯誤剖析查詢的問題。此修正適用於所有平台。
+ 修正 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 命令會截斷輸出的問題。
+ 已新增對用於描述外部 Kinesis 串流和 Kafka 主題之 \$1de 的支援。

*1.0.7 (2023-03-22)*

錯誤修正
+ 修正了 RSQL 無法描述具體化視觀表的問題。
+ 修正了使用 Amazon Redshift Serverless 時，stl\$1connection\$1log 上的許可遭拒錯誤。
+ 修正了 RSQL 可能無法正確處理 \$1GOTO 標籤的問題。
+ 修正了 SSL 訊息會以靜音模式列印的問題。
+ 修正了描述預存程序時會顯示隨機字元的問題。
+ 修正了會列印重複 ERROR/INFO 訊息的問題。

新增
+ RSQL 現在會直接從 ODBC 驅動程式取得 SSL 資訊。



*1.0.6 (2023-02-21)*

錯誤修正
+ 在 Redshift 修補程式 1.0.46086 (P173) 上修正了 \$1d 會擲出錯誤 (整數的輸入語法無效: "xid") 的問題。

新增
+ 已重新命名安裝檔案以反映支援的架構。



*1.0.5 (2022-06-27)*

錯誤修正
+ 將 SQL 錯誤訊息傳送到標準錯誤 (stderr)。
+ 修正了使用 ON\$1ERROR\$1STOP 時結束代碼所發生的問題。指令碼現在會在遇到錯誤後結束，並返回正確的結束代碼。
+ Maxerror 現在不區分大小寫。

新增
+ 已新增對 ODBC 2.x 驅動程式的支援。



*1.0.4 (2022-03-19)*
+ 新增對 RSPASSWORD 環境變數的支援。設定密碼以連線到 Amazon Redshift。例如 `export RSPASSWORD=TestPassw0rd`。



*1.0.3 (2021-12-08)*

錯誤修正
+ 修正了在 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 叢集。下列各節將引導您完成在使用和不使用資料來源名稱 (DSN) 搭配 RSQL 的情況下，建立與叢集的連線的步驟。

## 在不使用 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>* 是您在前一步驟中記錄的 **Endpoint (端點)**。
   +  *<username>* 是有許可而可以連線至叢集的使用者名稱。
   +  *<databasename>* 是您在前一步驟中記錄的 **Database Name (資料庫名稱)**。
   +  *<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>
```

### 搭配 IAM 設定檔使用 DSN 連線
<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` 金鑰的值是您從 CLI AWS 登入資料中選擇的具名設定檔。本範例示範名為 `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。

*Backup* 會指出在擷取快照時是否有備份資料表。有效值為 `YES` 或 `NO`。

*Created* 是建立資料表時的時間戳記。建立日期不適用於 2018 年 11 月之前建立的 Amazon Redshift 資料表。在此日期之前建立的資料表會顯示 n/a (不適用)。

*Unique Constraints* 會列出資料表上唯一的和主索引鍵的限制。

*Foreign-key constraints* 會列出資料表上的外部索引鍵限制。

## \$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 中繼存放區和來自 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>

 與 \$1dp 相同的輸出。

## \$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 content：

```
\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 content：

```
\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 content：

```
\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 content：

```
\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_tw/redshift/latest/mgmt/rsql-query-tool-error-codes.html)

資料例外狀況：

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

完整性限制違規：

[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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。如果未設定 RSPASSWORD，而且您使用 DSN 進行連線，則 RSQL 會從 DSN 檔案的參數中取得密碼。最後，如果未設定 RSPASSWORD，而且您沒有使用 DSN，則 RSQL 會在嘗試連線後提供密碼提示。

以下是設定 RSPASSWORD 的範例：

```
export RSPASSWORD=TestPassw0rd
```