SQL Insert Into Temp Table in both If and Else Blocks

后端 未结 8 1957
自闭症患者
自闭症患者 2020-12-10 12:52

I\'m trying to populate a temp table based on the result of a condition in SQL 2005. The temp table will have the same structure either way, but will be populated using a d

8条回答
  •  长情又很酷
    2020-12-10 13:38

    Here is a solution which I use if temp table can't be created upfront and don't want to put core logic in dynamic SQL.

    IF 1 = 1 -- Replace with actual condition
    BEGIN
        SELECT * INTO #tmp1 FROM dbo.Table1
    END
    ELSE
    BEGIN
        SELECT * INTO #tmp2 FROM dbo.Table2
    END
    
    -- Inserting data into global temp table so sql server can't complain on not recognizing in a context
    DECLARE @Command VARCHAR(MAX)
    IF OBJECT_ID('tempdb..#tmp1') IS NOT NULL
    BEGIN
        SET @Command = 'SELECT * INTO ##tmp FROM #tmp1'
    END
    ELSE
    BEGIN
        SET @Command = 'SELECT * INTO ##tmp FROM #tmp2'
    END
    
    EXECUTE(@Command)
    SELECT * INTO #tmpFinal FROM ##tmp -- Again passing data back to local temp table from global temp table to avoid seeing red mark
    
    IF OBJECT_ID('tempdb..##tmp') IS NOT NULL DROP TABLE ##tmp
    IF OBJECT_ID('tempdb..#tmp1') IS NOT NULL DROP TABLE #tmp1
    IF OBJECT_ID('tempdb..#tmp2') IS NOT NULL DROP TABLE #tmp2
    
    SELECT * FROM #tmpFinal
    
    IF OBJECT_ID('tempdb..#tmpFinal') IS NOT NULL DROP TABLE #tmpFinal
    

提交回复
热议问题