SELECT * FROM OPENQUERY(LOGDB, 'SELECT mac_address,heartbeats[1]->>'group_id' as group_id FROM hubs where location_key = 290 limit 10')
Well, does that look correct to you? You have these tokens: <string-literal> <Identifier> <string-literal>. But OPENQUERY only accepts a single string literal for the second argument. So the resulting statement should be:
SELECT * FROM OPENQUERY(LOGDB,
'SELECT mac_address,heartbeats[1]->>''group_id'' as group_id
FROM hubs where location_key = 290 limit 10')
That is, the single quotes around group_id
needs to be doubled.
Composing nesting dynamic SQL is difficult and in order to save your mind, you should work it out step by step. You will need to use the function quotestring.
SELECT @postgres =
concat('SELECT mac_address,heartbeats[1]->>', dbo.quotestring(@VARB), ' as group_id')
PRINT @postgres
FROM hubs where location_key = 290 limit 10')
SELECT @openquery = 'SELECT * FROM OPENQUERY(POSTGRES, ' +
dbo.quotestring_n(@postgres)
PRINT @postgres
PRINT @openquery
EXEC(@openquery)