数据设计如下
books表书籍表,每本书的有很多文章,保存在articles字段中
articles表包为文章表,每篇文章由多个人编辑完成(保存在authors列中)
author表包含作者信息
不使用游标,查询参与编写ID号为1的书的作者
结果为
id authorName
1 张三
2 李四
3 王五
4 小麦
5 小王
6 小李
各表数据
---------------------------------------------------------------
books表 数据如下
id articles
1 1,2,3
2 4,5,6
---------------------------------------------------------
articles 表数据如下
id authors
1 1,2,3
2 4,5,6
3 4,5,6
4 4,5,6
5 1,2,3
6 1,2,3
--------------------------------------------
author表 数据如下
id authorName
1 张三
2 李四
3 王五
4 小麦
5 小王
6 小李
USE tempdb
GO
CREATE TABLE BOOKS
(
ID INT IDENTITY(1,1) PRIMARY KEY NOT NULL,
ARTICLES NVARCHAR(20)
)
GO
INSERT INTO BOOKS
SELECT '1,2,3' UNION
SELECT '4,5,6'
GO
CREATE TABLE ARTICLES
(
ID INT IDENTITY(1,1) PRIMARY KEY NOT NULL,
AUTHORS NVARCHAR(20)
)
GO
INSERT INTO ARTICLES
SELECT '1,2,3' UNION
SELECT '4,5,6' UNION
SELECT '4,5,6' UNION
SELECT '4,5,6' UNION
SELECT '1,2,3' UNION
SELECT '1,2,3'
GO
CREATE TABLE AUTHORS
(
ID INT IDENTITY(1,1) PRIMARY KEY NOT NULL,
AUTHORNAME NVARCHAR(8)
)
GO
INSERT INTO AUTHORS
SELECT '张三' UNION
SELECT '李四' UNION
SELECT '王五' UNION
SELECT '小麦' UNION
SELECT '小王' UNION
SELECT '小李'
GO
SELECT * FROM BOOKS
SELECT * FROM ARTICLES
SELECT * FROM AUTHORS
GO
ALTER PROC GETBOOKAUTHORSBYID
@BOOKID INT
AS
DECLARE @SQL NVARCHAR(200),@ARTICLES NVARCHAR(20),@AUTHORS NVARCHAR(50)
SET @AUTHORS=''
SELECT @ARTICLES=ARTICLES FROM BOOKS WHERE ID=@BOOKID
SET @SQL = 'SELECT @A=@A+AUTHORS+'','' FROM ARTICLES WHERE ID IN ('+@ARTICLES+')'
EXEC SP_EXECUTESQL @SQL,N'@A NVARCHAR(50) OUT',@AUTHORS OUT
IF(LEN(@AUTHORS)>0)
BEGIN
SET @AUTHORS=SUBSTRING(@AUTHORS,0,LEN(@AUTHORS))
SET @SQL = 'SELECT ID,AUTHORNAME FROM AUTHORS WHERE ID IN ('+@AUTHORS+')'
EXEC(@SQL)
END
GO
EXEC GETBOOKAUTHORSBYID 1
你最终要查询的结果是什么?