从数据库中获取所选行的子记录

时间:2012-05-15 01:10:20

标签: sql-server sql-server-2008 tsql

我有3张这样的表

bug_groups

ID        NAME        DESCRIPTION
--------------------------------------
1         Group1      Some description
2         Group2      Some description
3         Group3      Some description

错误

ID        NAME        DESCRIPTION        BELONGSTO
--------------------------------------------------
1         Bug1        something          1
2         Bug2        something          1
3         Bug3        something          2

bug_comments

ID        BUGID       COMMENT
-----------------------------
1         1           something
2         1           something
3         2           something
4         2           something
5         3           something

我想创建一个存储过程,它将获得2个结果集,一个包含给定bug组的所有错误,另一个包含组中所有错误的所有注释。 BELONGSTO字段指定错误所属的组。因此,如果我想运行此查询,为错误组ID传入1,我希望这个结果

RESULT SET 1

ID        NAME         DESCRIPTION         BELONGSTO
----------------------------------------------------
1         Bug1         something           1
2         Bug2         something           1

RESULT SET 2

ID        BUGID        COMMENT
------------------------------
1         1           something
2         1           something
3         2           something
4         2           something

我想我可能需要使用临时表,但我不确定如何做到这一点。这就是我到目前为止(不起作用)

ALTER PROCEDURE bugs_getAllBugGroupData
    @groupid int
AS
BEGIN
    DECLARE @bugids TABLE (id int)
    INSERT @bugids
    SELECT id FROM bugs
    WHERE belongsto = @groupid

    SELECT * FROM bugs WHERE belongsto = @groupid
    SELECT * FROM bugs_comments WHERE bugid IN (@bugids)
END
GO

我得到的错误信息是“必须在最后一个select语句中声明标量变量@bugids”。

2 个答案:

答案 0 :(得分:2)

这一行

SELECT * FROM bugs_comments WHERE bugid IN (@bugids)

必须是

SELECT * FROM bugs_comments WHERE bugid IN (SELECT id FROM @bugids).

但是您不需要辅助表。您可以使用联接直接查询:

1

SELECT * FROM bugs WHERE belongsto = @groupid

2

SELECT * FROM bugs_comments AS bc
    INNER JOIN bugs AS b ON (bc.bugid = b.id)
    WHERE b.belongsto = @groupid

答案 1 :(得分:0)

更有效的方式是......

SELECT  ID,
        Name,
        Description,
        BelongsTo
  FROM  bugs
 WHERE  BelongsTo =  @groupid 

SELECT  bc.ID,
        bc.BugID,
        bc.Comment
  FROM  bug_comments bc
        JOIN bug b ON b.BugId = bc.BugID AND b.BelongsTo = @groupid