Share via

Using table parameter in dynamic sql

Thelma Obirieze 66 Reputation points
2021-02-24T22:59:23.59+00:00

Hi everyone,

I have a stored proc like this that throws the following error when I execute it

CREATE PROC Test  
  
AS   
  
DECLARE @Temp Table (ID int, Name Varchar(50))  
  
insert into @Temp  
VALUES   
(1, 'Adam'),  
(2, 'John'),  
(3, 'Andrew')  
  
DECLARE @sql NVARCHAR(MAX)  
SET  @sql = 'SELECT * FROM'+ @Temp  
  
EXEC(@Temp)  

Msg 1087, Level 15, State 2, Line 19
Must declare the table variable "@temp ".

Can someone help me figure this out.

Developer technologies | Transact-SQL
Developer technologies | Transact-SQL

A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.


2 answers

Sort by: Most helpful
  1. MelissaMa-msft 24,246 Reputation points Moderator
    2021-02-25T01:14:45.67+00:00

    Hi @Anonymous

    Welcome to Microsoft Q&A!

    You could also include the DDL of @temp in @alenzi in order to avoid this kind of error.

    Please also refer below:

    CREATE PROC Test   
    AS   
    BEGIN   
    DECLARE @sql NVARCHAR(MAX)  
    SET  @sql = N' DECLARE @Temp Table (ID int, Name Varchar(50))   
    insert into @Temp  
    VALUES   
    (1, ''Adam''),  
    (2, ''John''),  
    (3, ''Andrew'')  
    SELECT * FROM @Temp'   
    EXEC(@sql)  
    END   
    

    Then call this procedure as below:

    EXEC Test  
    

    Best regards
    Melissa


    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

  2. Guoxiong 8,221 Reputation points
    2021-02-24T23:36:10.41+00:00

    You can use a temporary table instead:

    CREATE PROC Test
    AS 
    
    CREATE TABLE #Temp (ID int, Name Varchar(50))
    
    INSERT INTO #Temp
    VALUES 
    (1, 'Adam'),
    (2, 'John'),
    (3, 'Andrew')
    
    SELECT * FROM #Temp
    
    DROP TABLE #Temp
    
    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.