> 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/19/client-interfaces/ecpg/ecpg-sql-commands/ecpg-sql-execute-immediate.md). Agents can also search and read this documentation through its [MCP server](https://docs.postgresql.tw/~gitbook/mcp).

# EXECUTE IMMEDIATE

### EXECUTE IMMEDIATE

EXECUTE IMMEDIATE — 動態準備並執行陳述式

### 語法

```

EXECUTE IMMEDIATE string
```

### 說明

`EXECUTE IMMEDIATE` 會立即準備並執行一個動態指定的 SQL 陳述式，但不擷取結果資料列。

### 參數

#### *`string`* [#](#ecpg-sql-execute-immediate-string) <a href="#ecpg-sql-execute-immediate-string" id="ecpg-sql-execute-immediate-string"></a>

包含要執行之 SQL 陳述式的字串常值或主機變數。

### 注意事項

一般使用時，*`string`* 是一個主機變數參照，指向包含動態建構之 SQL 陳述式的字串。使用字串常值的情況用處不大；你還不如直接撰寫該 SQL 陳述式，省去額外輸入 `EXECUTE IMMEDIATE`。

若你確實使用字串常值，請記住，你可能想在 SQL 陳述式中加入的任何雙引號，都必須寫成八進位跳脫序列（`\042`），而不是一般 C 慣用的 `\"`。這是因為該字串位於 `EXEC SQL` 區段內，因此 ECPG 詞法分析器會依 SQL 規則而非 C 規則來剖析它。任何內嵌的反斜線稍後會依 C 規則處理；但 `\"` 會被視為常值的結尾，因而立即造成語法錯誤。

### 範例

以下範例使用 `EXECUTE IMMEDIATE` 與名為 `command` 的主機變數，執行一個 `INSERT` 陳述式：

```

sprintf(command, "INSERT INTO test (name, amount, letter) VALUES ('db: ''r1''', 1, 'f')");
EXEC SQL EXECUTE IMMEDIATE :command;
```

### 相容性

SQL 標準規定了 `EXECUTE IMMEDIATE`。

***

原文：[PostgreSQL 18.6 Documentation](https://www.postgresql.org/docs/18/ecpg-sql-execute-immediate.html)（原文版本：18.6；核對日期：2026-10-18）


---

# 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 by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.postgresql.tw/19/client-interfaces/ecpg/ecpg-sql-commands/ecpg-sql-execute-immediate.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
