SQL Insert Into Temp Table in both If and Else Blocks

后端 未结 8 1933
自闭症患者
自闭症患者 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:27

    You could drop the table before SELECTing INTO it in both cases., e.g.:

    DECLARE @Id int 
    SET @Id = 1  
    
    IF (@Id = 2) BEGIN  
        IF OBJECT_ID('tempdb..#MyTestTable') IS NOT NULL DROP TABLE #MyTestTable
        SELECT 'ABC' AS Letters 
        INTO #MyTestTable; 
    END ELSE BEGIN 
        IF OBJECT_ID('tempdb..#MyTestTable') IS NOT NULL DROP TABLE #MyTestTable 
        SELECT 'XYZ' AS Letters 
        INTO #MyTestTable; 
    END 
    

    Update After Comment:

    That's annoying.

    How about two separate temp tables? Then after the If/Else login, check for the existence of each one and if it exists, select into a third temp table? That may not perform great, but whether that matters or not depends on what you need this for.

提交回复
热议问题