有人可以帮我解释这个TSQL代码吗?

时间:2010-12-15 06:39:54

标签: sql tsql

我得到了以下存储过程,但我是T-SQL的新手,并且不太确定它的语法。有人可以向我解释一下吗?

问题:

  • #tmp语法代表什么?
  • c.RootCategoryId中的c在哪里定义?

以下是代码:

ALTER PROCEDURE [dbo].[GetAllTopCategories]
    @prewin7 bit
AS
SELECT * INTO #tmp FROM dbo.fnGetCategories(@prewin7)

SELECT
    c.RootCategoryId CategoryId,
    c.CategoryName + ' [' + CAST(g.DiagnosticCount AS nvarchar(max)) + ']' CategoryName,
    @prewin7 as PreWin7
FROM (
    SELECT
        c.RootCategoryId CategoryId,
        SUM(c.DiagnosticCount) DiagnosticCount
    FROM #tmp c
    GROUP BY c.RootCategoryId
) g
INNER JOIN #tmp c ON c.CategoryId = g.CategoryId
ORDER BY c.CategoryName

DROP TABLE #tmp

2 个答案:

答案 0 :(得分:3)

#tmp是一个本地临时表,例如它只对创建它的连接可见,一旦连接消失,临时表也是如此。因此,最后DROP TABLE #tmp实际上不是必需的 - SQL Server会自动删除该表。

这个临时表是在这里创建的:

SELECT * INTO #tmp FROM dbo.fnGetCategories(@prewin7)

因此它将包含dbo.fnGetCategories存储函数的结果集将返回的任何行。

SELECT
    c.RootCategoryId CategoryId,
    SUM(c.DiagnosticCount) DiagnosticCount
FROM #tmp c

此处,数据是从该临时表中选择的,该表的别名为c - 因此,c.RootCategoryId必须是该临时表的列,因此它必须是从上面调用的存储函数返回的行。

答案 1 :(得分:0)

你真的需要临时表吗?

   ALTER PROCEDURE [dbo].[GetAllTopCategories]
        @prewin7 bit
    AS

    /*SELECT * INTO #tmp FROM dbo.fnGetCategories(@prewin7)*/

    SELECT
        c.RootCategoryId CategoryId,
        c.CategoryName + ' [' + CAST(g.DiagnosticCount AS nvarchar(max)) + ']' CategoryName,
        @prewin7 as PreWin7
    FROM (
        SELECT
            c.RootCategoryId CategoryId,
            SUM(c.DiagnosticCount) DiagnosticCount
        FROM (select * FROM dbo.fnGetCategories(@prewin7)) c
        GROUP BY c.RootCategoryId
    ) g
    INNER JOIN (select * FROM dbo.fnGetCategories(@prewin7)) c ON c.CategoryId = g.CategoryId
    ORDER BY c.CategoryName