如何在 SQL 服务器的 ELSE IF 语句中创建相同的临时 table?

How to create same Temporary table in ELSE IF Statement in SQL Server?

我在不同条件下使用 else if 语句将数据存储到 '#tempQuantity' temp table

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

执行此 Alter stored procedure 时,会抛出错误 "There is already an object named '#tempQuantity' in the database."

我理解错误。但它不会同时创建 2 个 temp table。那为什么会抛出。那么如何创建临时 table 像这样

备注

I couldn't drop too, before it creating table in second ELSE IF Statement

你应该试试

IF OBJECT_ID('tempdb..#tempQuantity') IS NULL
    SELECT * INTO #tempQuantity...
ELSE 
    INSERT INTO  #tempQuantity

如果您不需要来自临时 table 的数据,您可以删除来​​自临时 table 的现有数据。

  1. 您可以声明一个本地 table 并通过 insert into ... select...

    插入数据
    DECLARE @TempTb AS  TABLE (Id int)
    IF(@GroupId = 1)
    BEGIN
    
        INSERT INTO @TempTb
        SELECT 1
    END
    ELSE 
    BEGIN
    
        INSERT INTO @TempTb
        SELECT 1
    END 
    
  2. 或者您可以创建#temp table 并插入数据

    IF OBJECT_ID('tempdb..##temptb') IS NOT NULL 
        BEGIN
            DROP TABLE #temptb
        END
    
    CREATE TABLE #temptb (Id int) 
    
    IF(@GroupId = 1)
    BEGIN
    
        INSERT INTO #temptb
        SELECT 1
    END
    ELSE 
    BEGIN
    
        INSERT INTO #temptb
        SELECT 1
    END         
    

您需要先创建临时文件 table。

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

使用 table 变量不是一个好主意,因为它会产生性能问题。

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

-- 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

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