if语句中的临时表

时间:2012-07-29 21:46:48

标签: sql-server tsql

IF @someVariable = 0
BEGIN
    SELECT * 
    INTO #TempTable
    FROM MyTable
    WHERE Category="Something"
END
ELSE
BEGIN
    SELECT * 
    INTO #TempTable
    FROM MyTable
    WHERE Category="SomethingElse"
END
DROP TABLE #TempTable

提出"已经有一个名为' #ThotTable'在数据库中。有办法解决这个问题吗?

2 个答案:

答案 0 :(得分:4)

IF @someVariable = 0
BEGIN
   SELECT * 
   INTO #TempTable1
   FROM MyTable
   WHERE Category="Something"
   DROP TABLE #TempTable1
 END
ELSE
 BEGIN
   SELECT * 
   INTO #TempTable2
   FROM MyTable
   WHERE Category="SomethingElse"
   DROP TABLE #TempTable2
END

这样可行,但根据您可能需要的代码,可能不是最佳解决方案;但是在你的示例代码中它解决了这个问题。

可替换地:

SELECT * into #TempTable from MyTable where (1=0)

IF @someVariable = 0
   INSERT INTO #TempTable SELECT * FROM MyTable WHERE Category="Something"
ELSE
   INSERT INTO #TempTable SELECT * FROM MyTable WHERE Category="OtherSomething"

DROP TABLE #TempTable

答案 1 :(得分:2)

表变量是否符合您的需求......由于这些范围问题,我更喜欢这些。

DECLARE @TempTable TABLE (
    -- Your definition
)

IF @someVariable = 0
BEGIN
    INSERT INTO @TempTable (...)
    SELECT ...
    FROM MyTable
    WHERE Category="Something"
END
ELSE
BEGIN
    INSERT INTO @TempTable (...)
    SELECT ...
    FROM MyTable
    WHERE Category="SomethingElse"
END

或者您是否试图阻止必须明确定义列?你能否重构以事先确定条件:

DECLARE @Category varchar(100)
IF @someVariable = 0
BEGIN
    SET @Category = "Something"
END
ELSE
BEGIN
    SET @Category = "SomethingElse"
END

SELECT * 
INTO #TempTable
FROM MyTable
WHERE Category = @Category

DROP TABLE #TempTable