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

前端 未结 2 1547
太阳男子
太阳男子 2021-01-18 04:37

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]          


        
相关标签:
2条回答
  • 2021-01-18 05:01

    You can replace it by String_agg for example SQL Server stored procedure:

    STUFF((SELECT DISTINCT ', ' + CONVERT(VARCHAR,L.ROLE_SUB_CAT_ID) 
           FROM [PHS].[dbo].PHS_ADMIN_USER_ACCESS_DTL K,
                [PHS].[dbo].[PHS_ADMIN_USER_ROLE_SUB_CAT_MST] L
           WHERE L.ROLE_SUB_CAT_ID = K.ROLE_SUB_CAT_ID 
             AND K.UMC_ID = A.UMC_ID 
             AND K.CCR_ID = A.CCR_ID
           FOR XML PATH('')), 1, 1, '') AS ROLE_SUB_CAT_ID
    

    Convert it to postgresql like this:

    string_agg((SELECT distinct ', ' ||  cast(L.ROLE_SUB_CAT_ID as VARCHAR) FROM PHS.dbo.PHS_ADMIN_USER_ACCESS_DTL K,
              PHS.dbo.PHS_ADMIN_USER_ROLE_SUB_CAT_MST L
              WHERE L.ROLE_SUB_CAT_ID = K.ROLE_SUB_CAT_ID AND K.UMC_ID = A.UMC_ID AND K.CCR_ID=A.CCR_ID
              ), 1, 1, '') AS ROLE_SUB_CAT_ID
    
    0 讨论(0)
  • 2021-01-18 05:07

    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 |
    
    0 讨论(0)
提交回复
热议问题