2014-01-15 68 views
-3

我有三個表分隔值如逗號在SQL Server三個表

用戶

+--+------+ 
|Id|Name | 
+--+------+ 
|1 |Ram | 
+--+------+ 
|2 |Rama | 
+--+------+ 
|3 |Leesa | 
+--+------+ 
|4 |Kelvin| 
+--+------+ 

角色

+--+-------+ 
|Id|Name | 
+--+-------+ 
|1 |Admin | 
+--+-------+ 
|2 |FA  | 
+--+-------+ 
|3 |Testing| 
+--+-------+ 
|4 |IT  | 
+--+-------+ 

用戶角色

+--+-------+-------+ 
|Id|User Id|Role Id| 
+--+-------+-------+ 
|1 |1  |1  | 
+--+-------+-------+ 
|2 |1  |2  | 
+--+-------+-------+ 
|3 |2  |3  | 
+--+-------+-------+ 
|4 |2  |1  | 
+--+-------+-------+ 
|5 |3  |2  | 
+--+-------+-------+ 
|6 |3  |3  | 
+--+-------+-------+ 
|7 |4  |4  | 
+--+-------+-------+ 
|8 |4  |2  | 
+--+-------+-------+ 

從這些3我想要這樣的輸出表

+--+---------+--------+ 
|Id|User Name|Roles | 
+--+---------+--------+ 
|1 |Ram  |Admin,FA| 
+--+---------+--------+ 
+1

你試過了什麼? – nrsharma

+0

我試圖就這樣 –

+0

與CTE爲 ( 選擇a.id,c.name爲用戶1, b.name如基於role1 從一個的UserRole加入基於role1 B關於a.roleid = b.id加入第C USER1Ç .id = a.userid ) select user1,stuff((從cte UL1選擇','+ role1,其中UL1.user1 = UL.user1 ORDER BY user1 FOR XML PATH('')),1,2,' ')as [role1] from cte UL GROUP BY user1對不起答案Post box Not at show on my side所以... –

回答

0

您可以通過創建存儲過程來完成。

CREATE PROC UserRoles 
(
    @UserId int 
) 

AS 
begin 
DECLARE @roles NVARCHAR(MAX) = '' 
SELECT @roles = @roles + ',' + t.Roles 
    FROM (SELECT r.NAME AS Roles FROM [User Role] ur 
    Inner JOIN [ROLE] r ON r.Id = ur.RoleId 
    INNER JOIN User1 u ON u.Id = ur.UserID WHERE u.Id = @UserId) t 
    SET @roles = RIGHT(@roles, LEN(@roles)-1) 
SELECT u.Id AS ID, u.NAME AS UserName, @roles AS Roles FROM USER1 u WHERE u.Id = @UserId 

end 
0

我想爲將來的SQL標準提出一些函數CONCATROWS。

SELECT page_id,CONCATROWS('\n',partext) AS pagetext FROM paragraph ORDER BY parposition GROUP BY page_id

我不需要此功能,更比我燦count次......不,我需要很糟糕,但它會使生活變得更輕鬆。