How do I pass a variable in a MSSQL linked server query?

Posted on 2009-12-28
Last Modified: 2012-05-08
Hello experts,

I would like to pass a variable in a linked server query. I am using MSSQL 2008 SQL server management studio.

I am querying a linked server running a Progress database

This query works

select count('order') as 'Orders Entered' from Openquery(V2, 'select order from oe_head where ord_date = ''12/28/2009'' and company_oe = ''cc'' and rec_type = ''o''')

I would like to pass a variable DATE for the ord_date but can't seem to get the syntax correct

Any ideas?

Question by:pgeisler
    LVL 142

    Expert Comment

    by:Guy Hengel [angelIII / a3]
    you can only do that with dynamic sql, as OPENQUERY does (unfortunately) not allow a variable for the SQL ...

    Author Comment

    could you give an example?
    LVL 142

    Accepted Solution

    this should do....
    and yes, this is the "hell of quotes" :)
    declare @sql varchar(1000)
    declare @date varchar(20)
    declare @comp varchar(20)
    declare @rect varchar(20)
    set @date = '12/28/2009'
    set @comp = 'cc'
    set @rect = 'o'
    set @sql = 'select count([order]) as [Orders Entered] 
     from Openquery(V2, ''select order from oe_head where ord_date = ''''' + @date + ''''' and company_oe = '''''+ @comp + ''''' and rec_type = ''''' + @rect + ''''' '') '

    Open in new window


    Author Closing Comment

    Perfect example, it was the quote "hell of quotes" I was having trouble with.

    Featured Post

    Threat Intelligence Starter Resources

    Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

    Join & Write a Comment

    How to leverage one TLS certificate to encrypt Microsoft SQL traffic and Remote Desktop Services, versus creating multiple tickets for the same server.
    Load balancing is the method of dividing the total amount of work performed by one computer between two or more computers. Its aim is to get more work done in the same amount of time, ensuring that all the users get served faster.
    This videos aims to give the viewer a basic demonstration of how a user can query current session information by using the SYS_CONTEXT function
    Via a live example, show how to set up a backup for SQL Server using a Maintenance Plan and how to schedule the job into SQL Server Agent.

    746 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    16 Experts available now in Live!

    Get 1:1 Help Now