WernerCD
WernerCD

Reputation: 2157

SQL SP_EXECSQL @VAR to run a "dynamic" OpenQuery

I have an OpenQuery (Used in SQL2005 to run a query against a legacy database). I'm building the string to run so that I'll return the last 6 months of data.

The problem I'm having is with '||' to concat.

This works on the legacy system:

SELECT
    EVENT_DATE || ' ' || EVENT_TIME as EVENTDateTime
FROM
     EVENT

This Works in SQL2005 via Linked SQL Server:

Declare @Query nvarchar(MAX)
Set @Query = N'
    SELECT
        *
    FROM
        OPENQUERY(PATCOMLIVE,
             ''SELECT
                *
            FROM
                 root.ESDB_EVENT as EV
            ''
            ) as OpenQ';

exec sp_executesql @Query

This does NOT work:

Declare @Query nvarchar(MAX)
Set @Query = N'
    SELECT
        *
    FROM
        OPENQUERY(PATCOMLIVE,
             ''SELECT
                EVENT_DATE || '' '' || EVENT_TIME
            FROM
                 root.ESDB_EVENT as EV
            ''
            ) as OpenQ';

exec sp_executesql @Query

Nor does this:

                EVENT_DATE '|'| '' '' '|'| EVENT_TIME

I know I'm missing something simple... but the || for concating strings together is messing things up although it does work on the legacy system by itself.

Upvotes: 0

Views: 2380

Answers (1)

Lamak
Lamak

Reputation: 70638

You are right, it doesn't work cause its not sending a complete string to the OPENQUERY, you can try two things. First, concatenating the right ', it should be like this:

Set @Query = N'
    SELECT
        *
    FROM
        OPENQUERY(PATCOMLIVE,
             ''SELECT
                EVENT_DATE || '''' '''' || EVENT_TIME
            FROM
                 root.ESDB_EVENT as EV
            ''
            ) as OpenQ';

Or you can try concatenating those columns in SQL, like this:

Set @Query = N'
    SELECT
        *, EVENT_DATE + '' '' + EVENT_TIME
    FROM
        OPENQUERY(PATCOMLIVE,
             ''SELECT
                *
            FROM
                 root.ESDB_EVENT as EV
            ''
            ) as OpenQ';

Upvotes: 3

Related Questions