Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 INSERT with OPENQUERY and Parameter ???

Author  Topic 

Ogriv
Starting Member

40 Posts

Posted - 2012-03-29 : 08:33:19
Greetings,

I have a Linked Server that I can query using a passed parameter like this ( I am setting the variable just for testing) :


DECLARE @URN varchar(15)
DECLARE @MyString VARCHAR(MAX)

SET @URN = '1234567890'

SET @MyString = 'SELECT URN
,SEQNO
,MNEMONIC
FROM OrderList
WHERE URN = ''' + @URN + ''' '

SET @MyString = N'SELECT * FROM OPENQUERY(LINKSRV,''' + REPLACE(@MyString, '''', '''''') + ''')'

EXEC (@MyString)


This query will return something like this:


URN SEQNUM MNEMONIC
1234567890 1 ALIBABA
1234567890 3 SHAZAAM
1234567890 2 KABOOM



Now I would normally do something like this:


DECLARE @MyString VARCHAR(MAX)

DECLARE @workTB TABLE (
URN VARCHAR(MAX)
,SEQNO VARCHAR(MAX)
,Mnemonic VARCHAR(MAX)
)

INSERT INTO @workTB
(
URN
,SEQNO
,Mnemonic
)
SELECT * FROM OPENQUERY(LINKSRV,'SELECT URN
,SEQNO
,MNEMONIC
FROM OrderList
WHERE URN = '1234567890'

SELECT * FROM @WorkTB




But my problem is, This last approach is not dynamic and I need to utilize the passed parameter. But OPENQUERY does not just simply accept a parameter.

So due to my inexperience, I'm stuck. I need to query the Linked Server with a query that contains a passed parameter and then insert those results into a separate table. But I'm unsure of how to place the dynamically built query into the INSERT statement.

I appreciate any guidance.


visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2012-03-29 : 12:30:44
use sp_executesql to build and execute dynamic query and then use it with INSERT


INSERT INTO ...
EXEC sp_executesql ...


------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

Ogriv
Starting Member

40 Posts

Posted - 2012-03-29 : 14:03:17
Awesome visakh16! Worked perfectly!

Thank you very much for your time.
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2012-03-29 : 14:59:19
welcome

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -