这是一个完成的代码示例,您可以如何做到这一点(也包括其他人已经建议的内容)。这就是你要找的东西吗?
-- declare variables
declare @ParamterCurrencyAmount numeric(26, 2),
@ParameterRollingVisitSum int
-- declare table variable
declare @Books table
(
ISBN int not null primary key,
BookName varchar(255) not null
)
-- declare table variable
declare @Authors table
(
AuthorID int primary key not null,
AuthorName varchar(255) not null
)
-- declare table variable
declare @BookAuthorRelations table
(
BookAuthorRelations int not null primary key,
ISBN int not null,
AuthorID int not null
)
-- insert sample data
insert into @Books
(
ISBN,
BookName
)
select 1000, 'Book A' union all
select 2000, 'Book B' union all
select 3000, 'Book C'
insert into @Authors
(
AuthorID,
AuthorName
)
select 1, 'Jack' union all
select 2, 'Peter' union all
select 3, 'Donald'
insert into @BookAuthorRelations
(
BookAuthorRelations,
ISBN,
AuthorID
)
select 1, 1000, 1 union all
select 2, 1000, 2 union all
select 3, 1000, 3 union all
select 4, 2000, 1 union all
select 5, 2000, 2 union all
select 6, 3000, 1
-- get books (with stuff)
select distinct Books.BookName,
stuff(
(
select distinct ', ' + Authors.AuthorName
from @Authors Authors,
@BookAuthorRelations BookAuthorRelations
where BookAuthorRelations.AuthorID = Authors.AuthorID
and Books.ISBN = BookAuthorRelations.ISBN
for xml path(''), type
).value('.', 'NVARCHAR(MAX)')
, 1, 2,'') data
from @Books Books