1
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

提出“数据库中已经有一个名为'#TempTable'的对象。有没有办法解决这个问题?

4

2 回答 2

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
于 2012-07-29T21:59:40.500 回答
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
于 2012-07-29T21:56:36.350 回答