0

How I can execute two commands at the same time in SQL Server?

I want to get a row count of a table and some row according to the row count. For example I want to get row count of a table and assuming I want to get last 50 rows on a single page.

How can I do this?


EDIT 1):

Consider that I first get count and it return to me 100 and I want to get 80 to 100 recordsin this point another tansaction may delete 70 to 100 records and I can not get appropriate records

Arian
  • 12,793
  • 66
  • 176
  • 300
  • Does it have to be in two commands, or are you OK if it is just one? – Brian Webster Sep 05 '11 at 18:03
  • If you want to base your selection on the row count - you will need to **first** wait 'til the row count is done - you cannot do this in parallel anyway.... – marc_s Sep 05 '11 at 19:00

4 Answers4

2

Is your requirement to be efficient, or to execute a single command? These do not necessarily result in the same thing. For a good discussion on implementing efficient paging, see this article and this follow-up discussion. Don't re-invent the wheel, and don't assume that a single command that handles both is necessarily going to be more efficient than any other solution.

Aaron Bertrand
  • 272,866
  • 37
  • 466
  • 490
1
select * from tableName1 where column1=(select count(*) from tableName2)
x2.
  • 9,554
  • 6
  • 41
  • 62
1

If I understand correctly you want a query that do the count of all record in the table and at the same time get only 50 row. You can do that with something like this:

Select Top 50 Column1, column2, (Select count(ID) from table1) as total from Table1

Personally I would prefer to execute two queries. One for the count and one for the top 50 rows (much more efficient imo)

Iridio
  • 9,213
  • 4
  • 49
  • 71
1

An inline count my be evaluated many times or may give different results. A separate CROSS JOIN approach will give different results at some point

See for why with repro script: can I get count() and rows from one sql query in sql server?

;WITH aCTE AS
(
    SELECT
       *,
       COUNT(*) OVER () AS TotalRows,
       ROW_NUMBER OVER (ORDER BY SomeLatest DESC) AS rn
    FROM
       MyTable
) foo
SELECT
   *
FROM
   foo
WHERE
   rn <= 50
Community
  • 1
  • 1
gbn
  • 422,506
  • 82
  • 585
  • 676