将查询结果放入变量和 WITH 语句中

Iva*_*sev 1 sql-server t-sql

我需要将查询结果放入一个变量中。

只是一个查询,工作成功

DECLARE @count INT = (

SELECT count (*)
FROM [AdventureWorks].[Person].[Address]    
);

select @count;
Run Code Online (Sandbox Code Playgroud)

但是如果我需要WITH在查询中使用该语句,则会出现语法错误

DECLARE @count INT = (
   WITH person_address (id)
   as (
    SELECT AddressID
    FROM [AdventureWorks].[Person].[Address]
   )
   SELECT count (*)
   FROM person_address    
);

select @count;
Run Code Online (Sandbox Code Playgroud)

消息 156,级别 15,状态 1,第 2 行 关键字“WITH”附近的语法不正确。

消息 319,级别 15,状态 1,第 2 行 关键字“with”附近的语法不正确。如果此语句是公用表表达式、xmlnamespaces 子句或更改跟踪上下文子句,则前一条语句必须以分号终止。

消息 102,级别 15,状态 1,第 9 行 ')' 附近的语法不正确。

如果WITH在 SQL 语句中使用了子句,如何将查询值放入变量中?

McN*_*ets 6

在最后一个查询中分配变量。

DECLARE @count INT;

WITH person_address (id)
as (
    SELECT AddressID
    FROM [AdventureWorks].[Person].[Address]
   )
   SELECT @count = count (*)
   FROM person_address;

select @count;
Run Code Online (Sandbox Code Playgroud)
create table t (id int);

insert into t values
(1),(1),(2),(1),(2);

declare @cnt int;

with ct as
(
    select id from t
)
select
  @cnt = count(*)
from
  ct
where id = 1;

select @cnt;
 
Run Code Online (Sandbox Code Playgroud)
| (无列名) |
| ---------------: |
| 3 |

db<>在这里摆弄