我已經安裝下面的例子來說明
- 使用應用運算符與FOR XML PATH。我使用了一個外部應用程序,因爲有一個用戶不能訪問對象。
- 在下面的第一個查詢中,我在結果中避免了「XML實體」。請注意,對象名稱包含XML需要形成XML的字符。下面接着第二個查詢顯示,如果TYPE和.value的(......省略了會發生什麼
SQL Fiddle
MS SQL服務器2014架構設置:
CREATE TABLE Users
([Code] varchar(1), [UserName] varchar(4))
;
INSERT INTO Users
([Code], [UserName])
VALUES
('A', 'Aaaa'),
('B', 'Bbbb'),
('C', 'Cccc'),
('D', 'Dddd'),
('E', 'Eeee')
;
CREATE TABLE Objects
([Code] varchar(7), [Name] varchar(23))
;
INSERT INTO Objects
([Code], [Name])
VALUES
('ObjectA', 'Fred & Ginger Whizzbang'),
('ObjectB', 'The diamond<> cutter'),
('ObjectC', 'Whatever'),
('ObjectD', 'Blah de Blah')
;
CREATE TABLE ObjectAccess
([ID] int, [ObjectCode] varchar(7), [UserCode] varchar(1))
;
INSERT INTO ObjectAccess
([ID], [ObjectCode], [UserCode])
VALUES
(1, 'ObjectA', 'A'),
(2, 'ObjectA', 'B'),
(3, 'ObjectA', 'C'),
(4, 'ObjectB', 'D'),
(5, 'ObjectB', 'A'),
(6, 'ObjectB', 'B'),
(7, 'ObjectB', 'C'),
(8, 'ObjectC', 'B'),
(9, 'ObjectC', 'C'),
(10, 'ObjectC', 'D'),
(11, 'ObjectD', 'C'),
(12, 'ObjectD', 'D'),
(13, 'ObjectE', 'A'),
(14, 'ObjectF', 'D')
;
查詢1:
SELECT
Users.code
, Users.UserName
, oa.ObjectList
FROM Users
OUTER APPLY (
SELECT
STUFF
((
SELECT /* DISTINCT -- can be used here if required */
',' + Objects.Name
FROM ObjectAccess
INNER JOIN Objects ON ObjectAccess.ObjectCode = Objects.Code
WHERE ObjectAccess.UserCode = Users.Code
ORDER BY Objects.Name
FOR XML PATH (''), TYPE --<< nb!!
)
.value('.', 'varchar(max)') --<< nb!!
, 1, 1, '')
) AS oa (ObjectList)
Results:
| code | UserName | ObjectList |
|------|----------|--------------------------------------------------------------------|
| A | Aaaa | Fred & Ginger Whizzbang,The diamond<> cutter |
| B | Bbbb | Fred & Ginger Whizzbang,The diamond<> cutter,Whatever |
| C | Cccc | Blah de Blah,Fred & Ginger Whizzbang,The diamond<> cutter,Whatever |
| D | Dddd | Blah de Blah,The diamond<> cutter,Whatever |
| E | Eeee | (null) |
查詢2:
SELECT
Users.code
, Users.UserName
, oa.ObjectList
FROM Users
OUTER APPLY (
SELECT
STUFF
((
SELECT /* DISTINCT -- can be used here if required */
',' + Objects.Name
FROM ObjectAccess
INNER JOIN Objects ON ObjectAccess.ObjectCode = Objects.Code
WHERE ObjectAccess.UserCode = Users.Code
ORDER BY Objects.Name
FOR XML PATH ('')
)
, 1, 1, '')
) AS oa (ObjectList)
Results:
| code | UserName | ObjectList |
|------|----------|------------------------------------------------------------------------------|
| A | Aaaa | Fred & Ginger Whizzbang,The diamond<> cutter |
| B | Bbbb | Fred & Ginger Whizzbang,The diamond<> cutter,Whatever |
| C | Cccc | Blah de Blah,Fred & Ginger Whizzbang,The diamond<> cutter,Whatever |
| D | Dddd | Blah de Blah,The diamond<> cutter,Whatever |
| E | Eeee | (null) |
爲什麼不同組時由?爲什麼分組沒有任何聚合函數? – jarlh
對不起SQL Server 2014. – user3374841
我認爲你正在尋找Pivot操作http://www.databasejournal.com/features/mssql/converting-rows-to-columns-pivot-and-columns-to-rows-unpivot-in -sql-server.html –