1

我有 3 张这样的桌子

错误组

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

错误评论

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

我想创建一个存储过程,它将获得 2 个结果集,一个包含给定错误组的所有错误,一个包含该组中所有错误的所有注释。该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”。

4

2 回答 2

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
于 2012-05-15T01:13:08.900 回答
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
于 2012-05-15T01:17:07.177 回答