SQL Insert Into Temp Table in both If and Else Blocks

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

    In the scenario you provide you could do this

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

    But otherwise you will need to create the table before the if statement like this

    Create Table #MyTestTable (
      MyValue varchar(3)
    )
    IF (@Id = 2) BEGIN 
      Insert Into (MyValue)
      SELECT 'ABC' AS Letters;
    END ELSE BEGIN
      Insert Into (MyValue)
      SELECT 'XYZ' AS Letters;
    END
    

提交回复
热议问题