I am using sp_MSforeachtable
to get a rowcount of specific tables in my database. I want these ordered by name.
How do I add an ORDER BY
clause to sp_MSforeachtable
?
I understand this question is over 10 years old, but it has over 3000 visits and a bunch of wrong answers. I'm going to repurpose Chris R.'s answer in hopes of getting this marked as the accepted answer, instead of overly-complicated half-pages of SQL or "you can't" answers. I came here with the exact same question so it's still relevant and obviously not simple.
Use the @whereand
parameter to specify an ORDER BY
clause, The contents of that parameter are tacked on to the end of the internal SELECT
statement via a simple + @whereand
in the stored proc. And using 1
in ORDER BY 1
means to order by the first column.
sp_MSforeachtable @command1='SELECT COUNT(*) AS ''?'' FROM ?', @whereand = 'ORDER BY 1'