Syntax to PRINT the row counts using Dynamic SQL?

techresearch7777777 1,981 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 Other
0 comments No comments
{count} votes

Accepted answer
  1. LiHongMSFT-4306 31,566 Reputation points
    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 121.4K Reputation points MVP Volunteer Moderator
    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.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.