Using temporary tables in IF .. ELSE statements

Why does SQL Server insist that the temp table already exists! one or the other will happen !, so it never will be.

declare @checkvar  varchar(10)
declare @tbl TABLE( colx varchar(10) )
set @checkvar ='a'

INSERT  INTO @tbl (colx) VALUES('a')
INSERT  INTO @tbl (colx) VALUES('b')
INSERT  INTO @tbl (colx) VALUES('c')
INSERT  INTO @tbl (colx) VALUES('d')

IF @checkvar  is null  select colx INTO #temp1 FROM @tbl
ELSE select colx INTO #temp1 FROM @tbl WHERE colx =@checkvar

Error: the database already has an object with the name "# temp1".

Is there an elegant way around this? if @checkvar is null, I want the whole table otherwise, give me only the values ​​where @checkvar = something

EDIT: The column is varchar, not int.

+5
source share
4 answers

Can't you just rewrite the expression?

SELECT colx INTO #temp1 FROM @tbl WHERE (@checkvar IS NULL) OR (colx = @checkVar)
+5
source

temp , WHERE 1=0.

SELECT colx INTO #temp1 
FROM   @tbl 
WHERE  1 = 0  // this is never true

IF @checkvar  IS NULL
BEGIN 
    INSERT INTO #temp1 (colName)   
    SELECT colx FROM @tbl 
END
ELSE 
BEGIN 
    INSERT INTO #temp1 (colName)   
    SELECT colx 
    FROM   @tbl 
    WHERE  colx = @checkvar 
END
+6

, SELECT.. INTO .

, , , INSERT.

, Id :

CREATE TABLE #temp1 (colx ...)

DECLARE @checkvar  VARCHAR(10)
DECLARE @tbl TABLE( colx varchar(10) )
SET @checkvar ='a'

INSERT  INTO @tbl (colx) VALUES('a')
INSERT  INTO @tbl (colx) VALUES('b')
INSERT  INTO @tbl (colx) VALUES('c')
INSERT  INTO @tbl (colx) VALUES('d')

IF @checkvar IS NULL  
BEGIN
  INSERT INTO #temp1(colx)
  SELECT colx 
  FROM @tbl
END
ELSE 
BEGIN
  INSERT INTO #temp1(colx)
  SELECT colx 
   FROM @tbl WHERE colx =@checkvar
END

, OR, (OR are evil;)

/

+3
drop table #temp1

select colx into #temp1 
from @tbl
where (ISNULL(@checkvar,'0')='0' or [colx] = @checkvar )

@checkvar , where, . "0" , , @checkvar.

+2

All Articles