1

I am writing an dynamic Query in sqlserver 2005.

DECLARE @SQL3 VarChar(2000)                             
SET @SQL3 =' INSERT into @TableClub4 SELECT  ID from Clubcard   '  
print (@SQL3);
Exec (@SQL3);

Whenever it excutes it gives me an error

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

But I have defined the @TableClub4 table parameter.

Let me know the syntax, where I am going wrong?

2 Answers 2

2

You cannot use a declared table inside a dynamic sql block. You can do it like this:

CREATE TABLE #TableClub4
(
    ID INT
)
DECLARE @SQL3 VarChar(2000)                             
SET @SQL3 =' INSERT into #TableClub4 SELECT ID from Clubcard'
print  (@SQL3);
Exec (@SQL3);
DROP TABLE #TableClub4
Sign up to request clarification or add additional context in comments.

Comments

1

Your table variable is not known inside the dynamic sql, but you can rewrite it to this:

DECLARE @SQL3 VarChar(2000)                             
SET @SQL3 ='SELECT  ID from Clubcard'  
print (@SQL3);

INSERT into @TableClub4
Exec (@SQL3);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.