SQL Server Select COUNT without using aggregate function or group by

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-24 16:42:47

问题


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!


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/3368967/sql-server-select-count-without-using-aggregate-function-or-group-by

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!