SQL Server Select COUNT without using aggregate fu

2019-07-22 09:15发布

I'm in a very, very tight situation here. I have an SQL query running on SQL Server 2005:

SELECT col1,col2,col3 FROM myTable

Which of course gives:

col1 | col2 | col3
------------------
 1   |  a   | i
 2   |  b   | ii

etc

I need to, if possible, add a COUNT query so that it will return the number of records returned. I cannot use GROUP BY or an aggregate function (It's a very edge case on some very inflexible software).

Ideally, something like this:

SELECT col1,col2,col3,COUNT(NumberOfRows) as NumRows FROM myTable

col1 | col2 | col3| NumRows
---------------------------
 1   |  a   | i   | 2
 2   |  b   | ii  | 2

I realise that this is bad. And inefficient. And against all good practices. But I'm in a corner with software whose architecture was frozen in stone in 1991!

2条回答
太酷不给撩
2楼-- · 2019-07-22 09:35

Uuh so it turns out my collegue came back with an answer 30 seconds after asking the question.

The correct syntax is:

SELECT col1,col2,col3,@@ROWCOUNT as NumRows FROM myTable
查看更多
Summer. ? 凉城
3楼-- · 2019-07-22 09:45

Looks like using @@ROWCOUNT will return the number of rows processed by the previous query, so I'm not sure that this is a valid solution. I think this is because @@ROWCOUNT is internally set after the query is run, so it is best used after the query has already completed. Therefore, it won't return the number of rows processed by the query in which it is placed.

查看更多
登录 后发表回答