Stored Procedure to count rows

This topic contains 1 reply, has 2 voices, and was last updated by Avatar Ossian 2 years, 10 months ago.

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • Avatar
    hilsoe
    Participant
    #166728

    I am new to sql and I need a stored procedure that can count number of rows in a table. I have googled but it confuses me more then it helps me.

    Avatar
    Ossian
    Moderator
    #191457

    You will need to use dynamic SQL to accept your table name as a parameter

    Create your SP using this code:
    CREATE PROCEDURE dbo.sp_selectcount
    @tablename NVARCHAR(200) A
    S
    DECLARE [USER=”81696″]CMD[/USER] NVARCHAR (255)
    SET [USER=”81696″]CMD[/USER] = ‘SELECT count(*) from ‘ + @tablename
    EXEC sp_executesql [USER=”81696″]CMD[/USER][/CODE]

    Execute it using EXEC dbo.sp_selectcount(mytable)[CODE]CREATE PROCEDURE dbo.sp_selectcount
    @tablename NVARCHAR(200) A
    S
    DECLARE [USER=”81696″]CMD[/USER] NVARCHAR (255)
    SET [USER=”81696″]CMD[/USER] = ‘SELECT count(*) from ‘ + @tablename
    EXEC sp_executesql [USER=”81696″]CMD[/USER][/CODE]

    Execute it using EXEC dbo.sp_selectcount(mytable)

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.