如何在 SQL Server 中的 ELSE IF 语句中创建相同的临时表?

Lia*_*san 4 sql sql-server stored-procedures temp-tables

我使用else if如下语句在不同条件下将数据存储到“#tempQuantity”临时表中

IF(@GroupKey = 1)
BEGIN
    SELECT 
        ItemID,
        StoreID,
        sum(Qty) Quantity,
        sum(ExtendedPrice) ExtendedPrice,
        sum(ExtendedCost) ExtendedCost
    into #tempQuantity
    FROM 
        dbo.F_ItemDailySalesParent

    WHERE
        ((@DateFrom is null) or (Time>=@datefrom)) and ((@DateTo is null) or (Time<=@dateTo))
    GROUP BY ItemID,StoreID
END
ELSE IF(@GroupKey = 2)
BEGIN
    SELECT 
        Year(Time),
        ItemID,
        StoreID,
        sum(Qty) Quantity,
        sum(ExtendedPrice) ExtendedPrice,
        sum(ExtendedCost) ExtendedCost
    into #tempQuantity
    FROM 
        dbo.F_ItemDailySalesParent

    WHERE
        ((@DateFrom is null) or (Time>=@datefrom)) and ((@DateTo is null) or (Time<=@dateTo))
    GROUP BY Year(Time),ItemID,StoreID
END
ELSE
BEGIN
    SELECT 
        Year(Time),
        DATEPART(WEEK,Time),
        ItemID,
        StoreID,
        sum(Qty) Quantity,
        sum(ExtendedPrice) ExtendedPrice,
        sum(ExtendedCost) ExtendedCost
    into #tempQuantity
    FROM 
        dbo.F_ItemDailySalesParent

    WHERE
        ((@DateFrom is null) or (Time>=@datefrom)) and ((@DateTo is null) or (Time<=@dateTo))
    GROUP BY Year(Time),DATEPART(WEEK,Time),ItemID,StoreID
END
Run Code Online (Sandbox Code Playgroud)

执行此操作时Alter stored procedure,它会抛出错误“数据库中已存在一个名为 '#tempQuantity' 的对象。”

我理解这个错误。但它不会同时创建2个临时表。那为什么会抛出呢。那么我怎样才能创建这样的临时表

笔记

在第二个 ELSE IF 语句中创建表之前,我也不能删除

FLI*_*KER 5

您需要先创建临时表。

INSERT..INTO然后在任何语句中使用IF..ELSE

使用表变量不是一个好主意,因为它会带来性能问题。

要轻松创建临时表,请在脚本开头使用以下代码

-- check if table exists
IF OBJECT_ID('tempdb..#tempQuantity') IS NULL
    DROP TABLE #tempQuantity

-- simply create the temp table using 1=2 in where clause
SELECT 
    Year(Time),
    ItemID,
    StoreID,
    sum(Qty) Quantity,
    sum(ExtendedPrice) ExtendedPrice,
    sum(ExtendedCost) ExtendedCost
into #tempQuantity
FROM 
    dbo.F_ItemDailySalesParent
where 1=2
Run Code Online (Sandbox Code Playgroud)

然后在所有 IF 条件中使用INSERT..INTO而不是SELECT..INTO