SQL-变量赋值与其他列选择

SQL-变量赋值与其他列选择,sql,sql-server,tsql,Sql,Sql Server,Tsql,我试图使用公共表表达式获取记录和记录计数,但我想将记录计数存储在一个变量中,它当然会给我错误 不能使用为变量赋值的SELECT语句 与数据检索操作相结合 我正在尝试这样的东西 declare @count int ;with allRecords as ( -- query fetching all the records with many joins ), recordsCount as ( select count(*) as Total from allRecords

我试图使用公共表表达式获取记录和记录计数,但我想将记录计数存储在一个变量中,它当然会给我错误

不能使用为变量赋值的SELECT语句 与数据检索操作相结合

我正在尝试这样的东西

declare @count int

;with allRecords as 
(
   -- query fetching all the records with many joins
),
recordsCount as 
(
    select count(*) as Total from allRecords
)
select allRecords.*, @count=recordsCount.Total from allRecords, recordsCount 
where -- multiple conditions 
这方面有什么办法吗


实际上@count变量是我的存储过程的一个输出变量,所以我想返回结果并填充这个@count变量。你不能这样做。如果要获取select语句返回到变量中的行数,应使用内置全局变量:

更新:

那么,在这种情况下,我知道你没有其他选择,然后使用临时表:

SELECT /* columns */ INTO #tempTableName 
-- rest of the select statement

SELECT @Count = COUNT(*) 
FROM #tempTableName

SELECT * 
FROM #tempTableName 
WHERE <conditions>

DROP TABLE #tempTableName

我会在这里使用临时表或表变量。然后,您可以对select@count=count*from ALLCORDS和select*from ALLCORDS执行单独的语句

为什么要从ALLCORDS执行select,而不仅仅是从ALLCORDS中选择@count=count*作为总计?@xdd-已经尝试过,不起作用!给出语法错误。这也是不允许的。也尝试过其他不同的变体;使用allRecords as-query获取具有多个连接的所有记录从allRecords中选择@count=count*,但我也想选择allRecords.*,这是我在评论中问您的主要问题。如果过程返回count,为什么要选择?或者你想要额外的带有计数的行?我在问题中提到,我想要得到所有的记录以及它的计数。这是我的业务要求。你想做报告吗?不仅仅是选择。你能给出期望输出的例子吗?它不是报告!我在表中显示数据,因此我想显示结果以及其中的总记录感谢Zohar!但实际上,当我从allRecords中选择记录时,我放置了一些筛选器,因此@ROWCOUNT将给我筛选的行数,而我需要allRecords的原始行数
SELECT /* columns */ INTO #tempTableName 
-- rest of the select statement

SELECT @Count = COUNT(*) 
FROM #tempTableName

SELECT * 
FROM #tempTableName 
WHERE <conditions>

DROP TABLE #tempTableName
declare @count int

;with allRecords as 
(
   -- query fetching all the records with many joins
)
select @count = count(*) as Total from allRecords