Consider the following stored procedure:
CREATE PROCEDURE Test (@Table1 NVARCHAR (100), @Table2 NVARCHAR(100))
AS
BEGIN
SET NOCOUNT ON;
DECLARE @sSQL nvarchar(500);
SELECT @sSQL = N'SELECT * FROM ' + @Table1+' '+ @Table2
+ 'where '+@Table1+'.id = '+@Table2+'.id_dept';
EXEC sp_executesql @sSQL
END
I have tried to execute it using the following syntax (but I get an error):
exec Test @table1='dept', @table2='emp'
Edit:
Using the Gordon Linoff's answer:
alter PROCEDURE Test (
@Table1 NVARCHAR (100), @Table2 NVARCHAR(100))
AS
BEGIN
SET NOCOUNT ON;
DECLARE @sSQL nvarchar(500);
SELECT @sSQL = N'SELECT * FROM ' + @Table1 + ' JOIN '+ @Table2
+ ' ON '+ @Table1+'.id = '+ @Table2+ '.id_dept';
EXEC sp_executesql @sSQL;
END
and then the following throws an error:
exec Test @table1='dept', @table2='emp';
Here is the error:
Maximum stored procedure, function, trigger, or view nesting level exceeded (limit 32)