postgres dblink escape single quote

Phill Pafford picture Phill Pafford · Jul 7, 2011 · Viewed 12.8k times · Source

Related Link:

Here is my error:

ERROR:  type "e" does not exist

Here is my query:

SELECT *
FROM dblink('host=theHostName port=1234 dbname=theDBName user=theUser password=thePassword',
    E'SELECT field_1, 
    CASE WHEN field_2 IS NOT NULL 
    THEN \'inactive\' ELSE \'active\' 
    END AS field_status 
    FROM the_table 
     ') 
AS linkresults(field_1 varchar(20),field_2 varchar(8))

If I use double quotes, remove the backslash escape for the single quotes and remove the E before the SELECT statement

SELECT *
FROM dblink('host=theHostName port=1234 dbname=theDBName user=theUser password=thePassword',
    "SELECT field_1, 
    CASE WHEN field_2 IS NOT NULL 
    THEN 'inactive' ELSE 'active' 
    END AS field_status 
    FROM the_table 
     ") 
AS linkresults(field_1 varchar(20),field_2 varchar(8))

I get this:

NOTICE:  identifier "SELECT ..." will be truncated

And the I also get the ERROR as my query has been truncated.

I have escaped with dblink like this before, so is there a server setting or something I need to configure?

I know the query works just fine if I run it on the sql server itself, but not with dblink. Any thoughts?

Postgres version 8.4

Answer

niktrs picture niktrs · Jul 7, 2011

Try replacing \'inactive\' with ''inactive'' -- caution: two single quotes

   SELECT *
    FROM dblink('host=theHostName port=1234 dbname=theDBName user=theUser password=thePassword',
        'SELECT field_1, 
        CASE WHEN field_2 IS NOT NULL 
        THEN ''inactive'' ELSE ''active'' 
        END AS field_status 
        FROM the_table 
         ') 

AS linkresults(field_1 varchar(20),field_2 varchar(8))

Alternative (previous) solution

   SELECT *
    FROM dblink('host=theHostName port=1234 dbname=theDBName user=theUser password=thePassword',
        'SELECT field_1, 
        CASE WHEN field_2 IS NOT NULL 
        THEN E\'inactive\' ELSE E\'active\' 
        END AS field_status 
        FROM the_table 
         ') 

AS linkresults(field_1 varchar(20),field_2 varchar(8))