I want to query PostgreSQL database, which contains lists of info, for a simple count of current records from within MSSQL. The PG server is a linked server in MSSQL.
I know very little about Postgre but have enough to be dangerous. I created a simple query to reside inside a function as follows:
CREATE FUNCTION get_count(id text, division text, company integer, INOUT recCount integer) AS $$
BEGIN
recCount := (SELECT COUNT(0)
FROM test.inventory
WHERE inv_id = $1 AND div_code = $2 AND cmpy_no = $3);
END;
$$ LANGUAGE plpgsql;
I can query it all day long like this:
SET @Query = 'SELECT test.get_count(''' + @Id+ ''', ''' + @Div + ''', ' + CAST(@Company AS VARCHAR) +', ?);'
EXEC (@Query) AT POSTGRESQLTEST;
But I can’t assign it to a variable like this:
SET @i = EXEC (@Query) AT POSTGRESQLPROD;
-- Error: Incorrect syntax near the keyword 'EXEC'.
Office mates say store the value in a temp table, query it, then drop it. Not very efficent IMHO but it will get the job done.
So what else can I do? How can I leverage the INOUT parameter recCount from the PG server?
Edited with feedback from comments below.
I think this should work with
OpenQuery:As @Andriy pointed out, OpenQuery does not accept variables. For quasi-dynamic SQL you have to assemble the whole query string before you can execute it. You’ll have to double up single quotes around strings for that – twice!
Here is an example on .databasejournal.com how it can be done.
And @sighlent provided his solution below.
As an aside, concerning the plpgsql function:
You don’t seem to need an input value for
recCount. To simplify things a bit make that anOUTparameter instead ofINOUTand you’ll have one less input parameter: