> For the complete documentation index, see [llms.txt](https://docs.postgresql.tw/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.postgresql.tw/client-interfaces/ecpg/ecpg-sql-commands/ecpg-sql-declare-statement.md).

# DECLARE STATEMENT

### DECLARE STATEMENT

DECLARE STATEMENT — 宣告 SQL 陳述式識別字

### 語法

```

EXEC SQL [ AT connection_name ] DECLARE statement_name STATEMENT
```

### 說明

`DECLARE STATEMENT` 宣告 SQL 陳述式識別字。SQL 陳述式識別字可與連線相關聯；動態 SQL 陳述式使用該識別字時，會使用相關聯的連線執行。宣告的命名空間是預編譯單元，不允許對同一 SQL 陳述式識別字進行多次宣告。請注意，若預編譯器以 Informix 相容模式執行且已宣告 SQL 陳述式，便不能將 `database` 用作游標名稱。

### 參數

*`connection_name`* [#](#ECPG-SQL-DECLARE-STATEMENT-CONNECTION-NAME) : 由 `CONNECT` 命令建立的資料庫連線名稱。

```
可省略 `AT` 子句，但這樣的陳述式沒有意義。
```

*`statement_name`* [#](#ECPG-SQL-DECLARE-STATEMENT-STATEMENT-NAME) : SQL 陳述式識別字名稱，可以是 SQL 識別字或主機變數。

### 注意事項

只有在宣告實際放在動態陳述式之前時，此關聯才有效。

### 範例

```

EXEC SQL CONNECT TO postgres AS con1;
EXEC SQL AT con1 DECLARE sql_stmt STATEMENT;
EXEC SQL DECLARE cursor_name CURSOR FOR sql_stmt;
EXEC SQL PREPARE sql_stmt FROM :dyn_string;
EXEC SQL OPEN cursor_name;
EXEC SQL FETCH cursor_name INTO :column1;
EXEC SQL CLOSE cursor_name;
```

### 相容性

`DECLARE STATEMENT` 是 SQL 標準的擴充功能，但可用於知名的資料庫管理系統。

### 另請參閱

[CONNECT](/client-interfaces/ecpg/ecpg-sql-commands/ecpg-sql-connect.md), [DECLARE](/client-interfaces/ecpg/ecpg-sql-commands/ecpg-sql-declare.md), [OPEN](/client-interfaces/ecpg/ecpg-sql-commands/ecpg-sql-open.md)

***

原文：[PostgreSQL 18.6 Documentation](https://www.postgresql.org/docs/18/ecpg-sql-declare-statement.html)（英文原文，待翻譯）


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.postgresql.tw/client-interfaces/ecpg/ecpg-sql-commands/ecpg-sql-declare-statement.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
