6

I need to run a dynamic sql which uses table variable created in the scope of the parent. How do I pass table variable into dynamic sql in SQL2008 ?

1
  • Given the general nature of your question, perhaps you'll be well-served by this general exposition on dynamic sql? sommarskog.se/dynamic_sql.html Commented Aug 10, 2010 at 8:56

1 Answer 1

19

Here's an end-end example:

-- Define a custom TABLE type
CREATE TYPE IntegerTableType AS TABLE (ID INTEGER);

-- Fill a var of that type with some test data
DECLARE @MyTable IntegerTableType
INSERT @MyTable VALUES (1),(2),(3)

-- Now this is how you pass that var into dynamic statement
EXECUTE sp_executesql N'SELECT * FROM @MyTable', 
    N'@MyTable IntegerTableType READONLY', 
    @MyTable
Sign up to request clarification or add additional context in comments.

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.