[FIXED] Table name as parameter for Microsoft SQL Server procedure

Issue

I am trying to use a SQL Server procedure to create two tables with different names depending on whether a variable is yes (1) or no (0). Everything I've seen refers to temporary tables. I would like to store the table permanently in the database.

CREATE PROCEDURE DUALTYPE 
    @TableName nvarchar(18), @YesNo int 
AS 
BEGIN 
    SELECT * 
    INTO dbo.[@TableName] 
    FROM 
        (SELECT * FROM mytable
         WHERE dual = @YesNo) dualtab
END

EXEC DUALTYPE @TableName = 'dualtable' @YesNo = 0

The procedure executes, but it thinks my table name is @TableName. How do I tell it to use 'dualtable' instead?


Solution

The code below, using T-SQL, allows for different variable inputs using the same query. The output is then stored in different tables on the database. It is good for making unique samples based on different variable criteria.

The declare statements establish the variable type inputs. Those inputs are then defined using the set statements. 'Set @query' is a string which contains the relevant query (in this case, creating a table based on whether 'dual' is yes vs. no). Because the alterable parameters are contained in a string, they are defined using set @parm N'@...', and then connected to the actual variables in 'EXEC...@parms...'. The query below will produce a table named 'Yes' or 'No' if the YesNo variable is set to 1 or 0, respectively.

declare @TableName sysname;
declare @YesNo int;
declare @parms nvarchar(max);
declare @query nvarchar(max);

set @TableName = 'Yes'
set @YesNo = 1
set @query = '
    Select * into [mydb].dbo.' + QUOTENAME(@TableName) + '
    from 
    mytab
    where dual = @lvl'
set @parms = N'@lvl int'

EXEC sp_executesql @query, @parms, @lvl = @YesNo


Answered By - llsabang
Answer Checked By - Cary Denson (sql.easybugfix Admin)

Related Posts

Post a Comment