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

时间:2017-04-09 08:20:52

标签: sql sql-server stored-procedures temp-tables

我将数据存储到'#tempQuantity'使用else if语句在不同条件下使用临时表,如下所示

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时,会抛出错误&#34;已经有一个名为&#39;#tempQuantity&#39;在数据库中。&#34;

我理解错误。但它不会同时创建2个临时表。然后它为什么抛出。然后,我如何创建像这样的临时表

注意

  

在第二次ELSE IF声明中创建表格之前,我也无法放弃

3 个答案:

答案 0 :(得分:2)

  1. 您可以声明本地表并按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表并插入数据

    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         
    

答案 1 :(得分:2)

您需要先创建临时表。

然后在任何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

然后在所有IF条件中使用INSERT..INTO代替SELECT..INTO

答案 2 :(得分:0)

你应该试试

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

如果您不想要临时表中的数据,可以从临时表中删除现有数据。