pseudocode pseudocode - 1 month ago 12
SQL Question

How to write Select query with dynamic table name in Stored Procedure?

I am writing a stored-procedure. But the table name is dynamic in this procedure. I want to get row number from my variable table. But where will I set

@rownumber
with return of select query?

Create Proc update_eMail
(@tablename nvarchar(50),
@columnname nvarchar(50))
AS
Begin

Declare @q_getrowNumber NVARCHAR(MAX)
Declare @rownumber int
SELECT @rownumber = Count(ID) FROM quotename(@tablename) // doesnt work

END


Thanks in advance

Answer

You write wrong Procedure for dynamic query Try This. It will Work.

ALTER PROC update_eMail(@tablename NVARCHAR(50))
AS
BEGIN 
DECLARE @RowNumber NVARCHAR(MAX)=''

  set @RowNumber='select Count(ID) FROM '+@tablename+''
  exec(@RowNumber)
END

OR Try below Code in your Query

ALTER PROC update_eMail1
(
   @tablename NVARCHAR(50)
)
AS
BEGIN
     DECLARE @sql NVARCHAR(4000)= '',@rownumber INT
     SET @sql = 'SELECT @rownumber = Count(ID) FROM '+quotename(@tablename) 

   EXEC sp_executesql @sql, N'@rownumber int output',@rownumber OUTPUT

   SELECT @rownumber

END
Comments