August 24, 2007 at 10:48 am
I'm trying to write a stored proc that allows me to get some data from a linked server. If I write the following code, the procedure creates successfully:
AS
DECLARE
nvarchar(4000),
nvarchar(4000)
-- Construct the main sql statement
SELECT @sql = 'INSERT INTO @mytable SELECT * FROM OPENQUERY(MBZODBC, ''SELECT
DECLARE @mytable table (
int PRIMARY KEY,
nvarchar(50))
EXEC (@sql)
When I try to run this sproc with the following:
EXEC
sprocDealSelectDtlItem @dealId=1, @dealerId=30, @stocknum=500001
I get the following error:
Anybody know how to pass a table variable to dynamic sql? I tried using a @paramlist with sp_executesql but I still got the same undeclared variable error, but while trying to create the stored procedure and referring this time to the parameter to sp_executesql. Is there another way to do this? I've wasted a day fiddling with the syntax to try to get this to work. Please somebody help me!
August 24, 2007 at 11:13 am
Execute statements run under a different context, and table variables are not shared. You could try using a temporary table.
Regards,
Andras
August 24, 2007 at 11:16 am
Also see http://www.sqlservercentral.com/forums/shwmessage.aspx?forumid=149&messageid=393025
Regards,
Andras
August 24, 2007 at 12:13 pm
Why does this need to be dynamic SQL? I don't see anything in your code that would require dynamic SQL to accomplish.
August 24, 2007 at 3:13 pm
John, thanks for your reply. I've simplified the query significantly to focus on the part that's causing the error. Both the linked server and the main table (the vs alias) are dynamically added to the query in my full version. I've printed out the SQL statement just before execution and using it statically (i.e. not dynamically) it works fine.
August 24, 2007 at 3:46 pm
Thanks, Andras. Using temporary table seems to work OK.
Viewing 6 posts - 1 through 5 (of 5 total)
You must be logged in to reply to this topic. Login to reply