Syntax to PRINT the row counts using Dynamic SQL?

techresearch7777777 1,796 Reputation points
2024-04-24T18:57:32.9433333+00:00

Hello, what would be the syntax to PRINT the row counts using Dynamic SQL (in my case here need to get the row counts via a Linked Server View)

I would like to have this as a step in a SQL Agent job which after it runs it PRINTs the row counts in it's job step in case need to review afterwards.

Thanks in advance.

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
12,756 questions
0 comments No comments
{count} votes

Accepted answer
  1. CosmogHong-MSFT 23,321 Reputation points Microsoft Vendor
    2024-04-25T01:45:46.5966667+00:00

    Hi @techresearch7777777

    How about this:

    DECLARE @SQL_STRING NVARCHAR(MAX), @rows INT
    SET @SQL_STRING = 'Your SQL Code Here'
    EXEC sp_executesql @SQL_STRING
    SELECT @rows = @@ROWCOUNT
    PRINT '@rows = ' + CAST(@rows AS VARCHAR(10))
    

    Best regards,

    Cosmog Hong


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Erland Sommarskog 101.4K Reputation points MVP
    2024-04-24T20:54:59.59+00:00
    PRINT concat('Rowcount is ', @@rowcount, '.')
    

    Not sure why you would use dynamic SQL.

    Then again, I'm not sure what you are trying to do overall. Your post could benefit from some clarification.