Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'stuff' and 'for xml path('')' from SQL Server in Postgresql

I'm migrating some SQL Server 2008R2 queries to Postgresql 9.0 and I have some trouble with it. Here's the SQL Server query:

stuff((select ', '+p.[NAME] as 'data()' 
from BPROVIDERS_PROVIDER p, BORDER_ARTICLEORDERPROVIDER aop 
where p.OID = aop.PROVIDER for xml path('')),1,1,'')) as pNAMES

Reading SQL Server documentation I understand that this creates a comma separated list. I think that I can change stuff function to overlay function in Postresql'. Am I correct?

The second problem comes with SQL Server's for xml path with ('') as a parameter. It returns the values assigned to an attribute called pNAMES instead of create row elements. Is that correct?

Does Postgresql Query_to_xml() function with attribute tableforest = 'true' do the same?

Thank you.

like image 718
user1891262 Avatar asked Jan 02 '13 09:01

user1891262


People also ask

What is for XML path SQL?

We can use FOR XML PATH to prepare a comma-separated string from the existing data. Let's create an Authors table and insert a few records into it. In the data, we can see we have an ID column and the AuthorName column. If we just select the records, it gives the output in the following format.

What is the stuff function in SQL Server?

The STUFF function inserts a string into another string. It deletes a specified length of characters in the first string at the start position and then inserts the second string into the first string at the start position.

Does PostgreSQL support XML?

Again, according to the SQL standard, this is the only way to convert between type xml and character types, but PostgreSQL also allows you to simply cast the value. SET xmloption TO { DOCUMENT | CONTENT }; The default is CONTENT , so all forms of XML data are allowed.

How can I get SQL query results in XML?

You can optionally retrieve formal results of a SQL query as XML by specifying the FOR XML clause in the query. The FOR XML clause can be used in top-level queries and in subqueries. The top-level FOR XML clause can be used only in the SELECT statement.


1 Answers

You can use string_agg instead.

SQL Fiddle

PostgreSQL 9.1.6 Schema Setup:

create table T
(
  Name varchar(10)
);

insert into T values('Kalle');
insert into T values('Pelle');
insert into T values('Urban');

Query 1:

select string_agg(Name, ',') as Names
from T

Results:

|             NAMES |
---------------------
| Kalle,Pelle,Urban |
like image 189
Mikael Eriksson Avatar answered Sep 23 '22 01:09

Mikael Eriksson