Data Cogs Information Technology

posts - 131, comments - 251, trackbacks - 36

General

Search This Site

Powered by Google

Brisbane

Locations of visitors to this page

Information

Archives

Images

Blogs

CV etc.

Links For Me

If you've ever tried to use OPENQUERY to perform a passthrough query in SQL Server to a linked server, you have probably come across the limitations of this function.  It is VERY clunky if you are trying to pass variables or to get return parameters, etc:

Have a look at this article for some examples:

http://support.microsoft.com/kb/314520

A better method is described at the bottom of the article, which is to use sp_executesql.  This is really important if you need to assign values to a variable and then use that variable in the local server context.  Since there are no built-in global variables in T-SQL you would need to create a temp table and really hack a solution.  sp_executesql gives a much tidier method:

DECLARE @RoomDesc varchar(100)
EXEC linkedserver.master.dbo.sp_executesql
     N'SELECT @RoomDesc = eqnum
    FROM maxprod.dbo.equipmentspec
    WHERE orgid = ''XXX''
    AND siteid = ''YYY''
    AND alnvalue = ''Y''
    AND eqnum = @RoomKey',
     N'@RoomDesc VARCHAR(100) OUTPUT, @RoomKey INT',
     @RoomDesc OUTPUT,
     @RoomKey


UPDATE t
SET RoomID = @RoomKey,
RoomName = @RoomDesc
FROM mylocaltable t
WHERE t.EmployeeNo = @EmployeeNo

posted on Wednesday, January 23, 2008 12:20 PM

Feedback

# re: T-SQL - Passthrough query to a linked server using sp_executesql instead of OPENQUERY

When researching a manga or anime series I find myself checking both: the usual sites and Thompson’s Guide.
May Contain Spoilers
Blast is being scouted by a big time record label, and with Nana busy with negotiations, Hachi is feeling very left out. Takumi isn’t making her feel any better and the only things he’s interested in is sex. Feeling guilty because of Nobu’s confession, Hachi is at a new low. Does she throw away her childish dreams and stop seeing Takumi?
http://ralfir.com/index.php?id=114
http://hablon.info/index.php?id=26
http://piksels.info/index.php?id=98
http://magmoform.info/index.php?id=105
http://kislota2008.info/index.php?id=48
Will being with Nobu be the key to her happiness.

6/23/2008 7:34 PM | razgadka

# re: T-SQL - Passthrough query to a linked server using sp_executesql instead of OPENQUERY

very useful article indeed…
10/16/2008 7:53 PM | sql

Post Comment

Title  
Name  
Url
Comment   
Protected by Clearscreen.SharpHIPEnter the code you see: