选择逗号分隔值sql存储过程

时间:2014-06-30 19:12:09

标签: sql sql-server

我有三张桌子:

  1. book_shelf - > pkid和其他列

  2. book_author - > pkidfkid_book_shelffkid_author

  3. author - > pkidname

  4. 对于book_shelf中想要以逗号分隔的作者姓名的行。如果书架实体有两个作者,则在book_author表中插入两行。

    这是我试过的

    (select BookShelf.pkid as SrNo,stuff((select ',' + a.name
        from 
        lib.book_shelf bs inner join
        lib.book_author ba on bs.pkid=ba.fkid_book_shelf
        inner join lib.author a on a.pkid=ba.fkid_authors 
        for xml path ('')
    ), 1, 1, '') as Author from lib.book_shelf BookShelf)
    

    但它会为每个book_shelf行选择所有作者姓名。

1 个答案:

答案 0 :(得分:1)

希望这可以帮到你。

CREATE TABLE BookShelf(ID INT)
CREATE TABLE BookAuthor(ID INT, BookShelf INT, AuthorID INT)
CREATE TABLE Author(ID INT, Name VarChar(50))
GO

INSERT INTO BookShelf VALUES(1)
INSERT INTO BookShelf VALUES(2)

INSERT INTO Author VALUES(1,'Author1')
INSERT INTO Author VALUES(2,'Author2')
INSERT INTO Author VALUES(3,'Author3')
INSERT INTO Author VALUES(4,'Author4')


INSERT INTO BookAuthor VALUES(1,1,1)
INSERT INTO BookAuthor VALUES(1,1,2)
INSERT INTO BookAuthor VALUES(1,2,3)
INSERT INTO BookAuthor VALUES(1,2,4)

SELECT 
    BookShelf.ID, 
    STUFF((SELECT ',' + Author.Name FROM BookAuthor INNER JOIN Author ON BookAuthor.AuthorID = Author.ID WHERE BookAuthor.BookShelf = BookShelf.ID FOR XML PATH('')),1,1,'')
FROM 
    BookShelf