# SQL Server - Query

> 在 Microsoft SQL Server 数据库上执行 SQL 查询和存储过程。

Source: https://docs.sommatic.ai/zh/nodes/integrations.microsoft.sqlserver.query/

- 标识: `integrations.microsoft.sqlserver.query`
- 类别: 集成
- 版本: 1.0.0
- 状态: 可用
- 执行方式: async

在 Microsoft SQL Server 数据库上执行 SQL 查询和存储过程。

连接你的 SQL Server 实例（本地部署或 Azure SQL），使用 @paramName 绑定运行参数化查询以防止 SQL 注入。支持连接池和自动清理。

**操作：**
- **SELECT：** 通过过滤、连接和聚合从表中获取行。
- **INSERT：** 向表中添加新记录。
- **UPDATE：** 修改满足条件的现有记录。
- **DELETE：** 从表中删除记录。
- **存储过程：** 使用命名输入参数执行存储过程。
- **DDL：** 执行 CREATE、ALTER、DROP 语句以管理 schema。

## 配置

- `connection_id` (string, 必填): SQL Server / Azure SQL 实例的凭据。接受 `connection-string`（`Server=...;Database=...;User Id=...;Password=...;`）或 `basic-auth`（用户名 + 密码 + 服务器 + 数据库）类型的凭据。
- `sql` (string, 必填, 支持表达式): 要执行的 SQL 语句或存储过程调用（例如“SELECT * FROM users WHERE id = @id”）。
- `parameters` (array, 可选): 用于参数化查询绑定的 { name, type, value } 对象数组。

## 输出端口

- `out` (默认): 查询返回的结果行
- `error`: 执行期间发生错误

## 输入契约

- `connection_id` (string, 必填)
- `sql` (string, 必填)
- `parameters` (array, 可选)

## 输出契约

- `result` (array<object>, 可选): 查询返回的行数组

## 在表达式中

后续节点可通过 `$("SQL Server - Query").item.json.<路径>` 读取此节点输出中的内容（请把 `SQL Server - Query` 换成你的节点标签）。**Editor** 标记工作流编辑器在 Previous Nodes 中提示的路径（输出契约）；**Worker** 标记 worker 实际通过 `out` 返回的路径，依据“端口”一节所示的输出。

- `$("SQL Server - Query").item.json.result` (array) = `[…] (1)`: 查询返回的行数组


## 工作原理

在 SQL Server 或 Azure SQL 上执行一条带命名 `@` 参数的 SQL 语句，并将第一个结果集的行放在 `result` 中返回。

1. 解析节点配置中的表达式。`connection_id`、`sql`、`parameters` 为空时，从输入项的同名字段读取。
2. 在服务端解析凭据：`connection-string` 凭据原样交给驱动；`basic-auth` / `object` 凭据从凭据配置或密钥中读取 `username`（或 `user`）、`password`、`server` 或 `host`、`database` 以及 `port`（默认 1433）。
3. 连接时启用加密（仅 localhost 关闭），并信任服务器证书。
4. 将 `parameters` 绑定为命名输入，执行 `sql`，关闭连接，并返回包含第一个结果集的 `{ result }`（语句不返回行时为空数组）。

## 在工作流中

### 节点

```json
{
  "node_id": "node-find-customer",
  "label": "Find customer",
  "operator_slug": "integrations.microsoft.sqlserver.query",
  "operator_version": "1.0.0",
  "config": {
    "connection_id": "pi-credential-xxxx",
    "sql": "SELECT id, email, status FROM customers WHERE id = @id",
    "parameters": [
      {
        "name": "id",
        "value": "{{ $json.customer_id }}"
      }
    ]
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "result": [
      {
        "id": 42,
        "email": "ana@example.com",
        "status": "active"
      }
    ]
  },
  "port": "out"
}
```

## 输出端口 (代码中的行为)

### `out`

语句已执行。无结果行的查询以及 UPDATE 等语句也从这里输出，`result` 为 `[]`。

```json
{
  "result": [
    {
      "id": 42,
      "email": "ana@example.com",
      "status": "active"
    }
  ]
}
```

### `error`

校验、凭据解析、连接或语句执行失败。

```json
{
  "error": "Must declare the scalar variable \"@id\"."
}
```

## 代码中的行为

- `parameters`: 接受 `{ name, value }` 数组或普通对象 `{ "id": 42 }`。`type` 字段会被忽略：驱动根据 JavaScript 值推断 SQL 类型。参数名不带 `@`。
- `connection_id`: 包含 `;`、`localhost` 或 `127.0.0.1` 的值会被解析为内联 JSON 连接设置并跳过凭据库，因此直接写入 ADO 风格的连接字符串会出现 JSON 解析错误。请将连接字符串保存为 `connection-string` 凭据。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `connection_id is required` | `error` | 配置和输入项中都没有凭据。 |
| `sql query is required` | `error` | `sql` 为空。 |
| `Credential <connection_id> has unsupported type '<type>' for integrations.microsoft.sqlserver.query. Use 'connection-string' or 'basic-auth'.` | `error` | 本节点不支持该凭据类型。 |
| `Must declare the scalar variable "@<name>".` | `error` | `sql` 使用了未在 `parameters` 中提供的参数。 |
| `Login failed for user '<user>'.` | `error` | 凭据中的用户名或密码错误。 |

## 说明与限制

- 只返回第一个结果集，不会暴露 `rowsAffected` 和输出参数。如需取回写操作的值，请使用 `OUTPUT` 或在末尾加 `SELECT`。
- 每次运行都会新建并关闭连接，采用驱动的默认超时设置，节点不会重试。


## 契约（JSON Schema）

### All (`*.definition.js`)

```json
{
  "slug": "integrations.microsoft.sqlserver.query",
  "name": "SQL Server - Query",
  "category": "integrations",
  "group": [
    {
      "key": "microsoft",
      "name": "Microsoft",
      "icon_url": "/icons/integrations/microsoft/microsoft.svg"
    },
    {
      "key": "sql-server",
      "name": "SQL Server",
      "icon_url": "/icons/integrations/microsoft/sql-server.svg"
    }
  ],
  "icon_url": "/icons/integrations/microsoft/sql-server.svg",
  "version": "1.0.0",
  "description": "Execute SQL queries and stored procedures on Microsoft SQL Server databases.\n\n  Connect your SQL Server instance (on-premise or Azure SQL) and run parameterized queries with @paramName binding for SQL injection prevention. Supports connection pooling and automatic cleanup.\n\n  **Operations:**\n  - **SELECT:** Fetch rows from tables with filters, joins, and aggregations.\n  - **INSERT:** Add new records to tables.\n  - **UPDATE:** Modify existing records matching a condition.\n  - **DELETE:** Remove records from tables.\n  - **Stored Procedures:** Execute stored procedures with named input parameters.\n  - **DDL:** Execute CREATE, ALTER, DROP statements for schema management.",
  "capabilities": [
    "sql",
    "database",
    "mssql",
    "microsoft",
    "azure"
  ],
  "config_schema": {
    "type": "object",
    "properties": {
      "connection_id": {
        "type": "string",
        "title": "SQL Server Credential",
        "description": "Credential for your SQL Server / Azure SQL instance. Accepts credentials of type `connection-string` (`Server=...;Database=...;User Id=...;Password=...;`) or `basic-auth` (username + password + server + database).",
        "ui_widget": "connection_picker",
        "ui_options": {
          "credential_types": [
            "connection-string",
            "basic-auth"
          ],
          "types": [
            "mssql"
          ]
        }
      },
      "sql": {
        "type": "string",
        "title": "SQL Query",
        "description": "The SQL statement or stored procedure call to execute (e.g., \"SELECT * FROM users WHERE id = @id\").",
        "format": "expression",
        "ui_widget": "sql_editor"
      },
      "parameters": {
        "type": "array",
        "title": "Query Parameters",
        "description": "Array of { name, type, value } objects for parameterized query binding."
      }
    },
    "required": [
      "connection_id",
      "sql"
    ]
  },
  "input_contract_schema": {
    "type": "object",
    "properties": {
      "connection_id": {
        "type": "string"
      },
      "sql": {
        "type": "string"
      },
      "parameters": {
        "type": "array"
      }
    },
    "required": [
      "connection_id",
      "sql"
    ]
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "result": {
        "type": "array",
        "items": {
          "type": "object"
        },
        "description": "Array of rows returned by the query"
      }
    }
  },
  "ports": [
    {
      "port_id": "out",
      "label": "Rows",
      "description": "Resulting rows from the query",
      "is_default": true,
      "supports_condition": true
    },
    {
      "port_id": "error",
      "label": "Error",
      "description": "Error occurred during execution",
      "is_default": false,
      "supports_condition": false
    }
  ],
  "execution_mode": "async",
  "required_resources": [],
  "compatible_worker_pools": [
    "standard-io",
    "db-io"
  ],
  "tags": [
    "sql",
    "database",
    "microsoft"
  ],
  "is_stateful": false,
  "publisher": {
    "identity": "org_sommatic_ai",
    "profile": {
      "name": "Sommatic AI",
      "verified": true,
      "url": "https://sommatic.ai",
      "logo_url": null
    }
  }
}
```

### config_schema

```json
{
  "type": "object",
  "properties": {
    "connection_id": {
      "type": "string",
      "title": "SQL Server Credential",
      "description": "Credential for your SQL Server / Azure SQL instance. Accepts credentials of type `connection-string` (`Server=...;Database=...;User Id=...;Password=...;`) or `basic-auth` (username + password + server + database).",
      "ui_widget": "connection_picker",
      "ui_options": {
        "credential_types": [
          "connection-string",
          "basic-auth"
        ],
        "types": [
          "mssql"
        ]
      }
    },
    "sql": {
      "type": "string",
      "title": "SQL Query",
      "description": "The SQL statement or stored procedure call to execute (e.g., \"SELECT * FROM users WHERE id = @id\").",
      "format": "expression",
      "ui_widget": "sql_editor"
    },
    "parameters": {
      "type": "array",
      "title": "Query Parameters",
      "description": "Array of { name, type, value } objects for parameterized query binding."
    }
  },
  "required": [
    "connection_id",
    "sql"
  ]
}
```

### input_contract_schema

```json
{
  "type": "object",
  "properties": {
    "connection_id": {
      "type": "string"
    },
    "sql": {
      "type": "string"
    },
    "parameters": {
      "type": "array"
    }
  },
  "required": [
    "connection_id",
    "sql"
  ]
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "result": {
      "type": "array",
      "items": {
        "type": "object"
      },
      "description": "Array of rows returned by the query"
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "out",
    "label": "Rows",
    "description": "Resulting rows from the query",
    "is_default": true,
    "supports_condition": true
  },
  {
    "port_id": "error",
    "label": "Error",
    "description": "Error occurred during execution",
    "is_default": false,
    "supports_condition": false
  }
]
```
