且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Sql Server - 子查询中的用户 CTE

更新时间:2023-02-02 22:46:41

在 SQL Server 中,CTE 必须位于查询的顶部.如果您动态构建查询,则除了查询之外,您还可以存储 CTE 列表.在将查询发送到 SQL 服务器之前,您可以在查询前加上 CTE 的列表:

In SQL Server, CTE's must be at the top of the query. If you construct queries dynamically, you could store a list of CTE's in addition to the query. Before you send the query to SQL server, you can prefix the query with a list of CTE's:

; with Cte1 as (...definition 1...),
  Cte2 as (...definition 2...),
  Cte3 as (...definition 3...),
  ...
...constructed query...

这是假设您在 SQL Server 之外构建 SQL.

This is assuming that you're constructing the SQL outside of SQL Server.

您也可以考虑创建视图.视图可以包含 CTE,它们可以用作子查询或派生表.如果您不经常生成 SQL(例如仅在安装期间或作为部署的一部分),视图是一个不错的选择.

You could also consider creating views. Views can contain CTE's, and they can be used as a subquery or derived table. Views are a good choice if you generate SQL infrequently, say only during an installation or as part of a deployment.