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 ?
A:
Something like this should do it:
EXECUTE sp_executesql
N'SELECT * FROM @table',
N'@table varchar(50)',
@table= 'MyTableName';
Further information on sp_executeSQL can be found here
I would also recommend that you read this article from Erland Sommarskog
Barry
2010-08-10 08:58:08
Barry that was not the question
Bobb
2010-08-10 09:38:03
+5
A:
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
AdaTheDev
2010-08-10 09:01:55