MS SQL组合选择一个char分隔符字符串

时间:2017-11-14 13:48:31

标签: sql-server tsql sql-server-2016

嘿这一切都是我的问题:

SELECT 
    uT.employeeID + '|' + uT.lastFirstMiddle + '|' + uT.ntName + '|' + 
    uT.email + '|' + uT.firstName + '|' + uT.lastName + '|' + uT.active, 
    (
        SELECT 
            ',' + uP.type
        FROM 
            usersPermissions AS uP
        WHERE 
            ',' + uT.userPerms + ',' 
        LIKE 
            '%,' + cast(uP.id AS nvarchar(20)) + ',%'
        FOR 
            XML PATH(''), TYPE
    ).value('substring(text()[1], 2)', 'varchar(max)') AS userPerms,
    (
        SELECT 
            ',' + uP.name
        FROM 
            pagePermissions AS uP
        WHERE 
            ',' + uT.userPerms + ',' 
        LIKE 
            '%,' + cast(uP.id AS nvarchar(20)) + ',%'
        FOR 
            XML PATH(''), TYPE
    ).value('substring(text()[1], 2)', 'varchar(max)') AS userPermPages
FROM 
    usersTbl as uT 
WHERE 
    uT.id = '1';

我要做的是将所有这些组合成一个输出

所以不要这样:

(No Column Name)                                                       |userPerms         |userPermsPages
-----------------------------------------------------------------------+------------------+-----------------------------
R98T92C48|Barker, Bob|bbarker|bbarker@priceisright.com|Bob|Barker|true |Read,Upload,Admin |ANP Index,BOM import,BOM line

我想要更多的内容:

(No Column Name)
-----------------------------------------------------------------------------------------------------------------------
R98T92C48|Barker, Bob|bbarker|bbarker@priceisright.com|Bob|Barker|true|Read|Upload|Admin|ANP Index|BOM import|BOM line

那么查询如何看起来像上面的例子一样输出它?

1 个答案:

答案 0 :(得分:1)

您是否尝试将该查询包装在CTE或Derived表中并从中进行选择

SELECT X.firstCol + X.userPerms + X.userPermPages
FROM
(
    SELECT 
        uT.employeeID + '|' + uT.lastFirstMiddle + '|' + uT.ntName + '|' + 
        uT.email + '|' + uT.firstName + '|' + uT.lastName + '|' + uT.active AS firstCol, 
        (
            SELECT 
                ',' + uP.type
            FROM 
                usersPermissions AS uP
            WHERE 
                ',' + uT.userPerms + ',' 
            LIKE 
                '%,' + cast(uP.id AS nvarchar(20)) + ',%'
            FOR 
                XML PATH(''), TYPE
        ).value('substring(text()[1], 2)', 'varchar(max)') AS userPerms,
        (
            SELECT 
                ',' + uP.name
            FROM 
                pagePermissions AS uP
            WHERE 
                ',' + uT.userPerms + ',' 
            LIKE 
                '%,' + cast(uP.id AS nvarchar(20)) + ',%'
            FOR 
                XML PATH(''), TYPE
        ).value('substring(text()[1], 2)', 'varchar(max)') AS userPermPages
    FROM 
        usersTbl as uT 
    WHERE 
        uT.id = '1'
) X ;