1

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

3 Answers 3

4

Here is one way to achieve the goal using dynamic sql

declare @sql NVARCHAR(4000)= '' set @sql = 'SELECT @rownumber = Count(ID) FROM '+ quotename(@tablename) exec sp_executesql @sql, N'@rownumber int output',@rownumber output 
Sign up to request clarification or add additional context in comments.

1 Comment

I update like this, but code finish in this line : ''exec sp_executesql @sql, N'@rownumber int output',@rownumber output '' The rest of my code doesn't work.
3

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 

4 Comments

If I write some codes after the 'EXEC' code line, does it work? Is there run only one EXEC method in one stored procedure?
Yes, It works. You can write codes after 'Exec' code line.
You can run multiple stored procedure inside another stored procedure its limit upto 32 levels
Maximum stored procedure, function, trigger, or view nesting level exceeded (limit 32)
0

This one will be easiest for you:

Create Proc update_eMail @tablename nvarchar(50) AS Begin EXEC ( 'SELECT Count(ID) FROM '+@tablename+'') END 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.