数据库中已经有一个名为“#t1”的对象

时间:2018-01-23 02:53:14

标签: tsql sql-server-2014

我在一个数据库中运行它(通过SSMS)我有写访问权限(定义了tmp模式),它运行正常:

DECLARE @i INT=1
WHILE @i < 5
BEGIN
    PRINT @i;

    IF OBJECT_ID('tmp.t1') IS NOT NULL 
    BEGIN
        DROP TABLE tmp.t1;
    END
    SELECT TOP 3 * INTO tmp.t1 FROM sys.all_columns ac

    IF OBJECT_ID('tmp.t1') IS NOT NULL 
    BEGIN
        DROP TABLE tmp.t1;
    END
    SELECT TOP 3 * INTO tmp.t1 FROM sys.all_objects ao

    IF OBJECT_ID('tmp.t1') IS NOT NULL 
    BEGIN
        DROP TABLE tmp.t1;
    END
    SELECT TOP 3 * INTO tmp.t1 FROM sys.all_parameters ap

    SET @i+=1
END

我在一个我没有创建表访问权限的数据库中运行它,并且在编译期间它失败了。

DECLARE @i INT=1
WHILE @i < 5
BEGIN
    PRINT @i;

    IF OBJECT_ID('tempdb..#t1') IS NOT NULL 
    BEGIN
        DROP TABLE #t1;
    END
    SELECT TOP 3 * INTO #t1 FROM sys.all_columns ac

    IF OBJECT_ID('tempdb..#t1') IS NOT NULL 
    BEGIN
        DROP TABLE #t1;
    END
    SELECT TOP 3 * INTO #t1 FROM sys.all_objects ao

    IF OBJECT_ID('tempdb..#t1') IS NOT NULL 
    BEGIN
        DROP TABLE #t1;
    END
    SELECT TOP 3 * INTO #t1 FROM sys.all_parameters ap

    SET @i+=1
END
我显然放弃了桌子;如果有什么我期望运行时错误但不是编译错误。

1 个答案:

答案 0 :(得分:1)

它是一种编译器行为,它只能接受SELECT INTO上的临时表才能使用一次。

  IF OBJECT_ID('tempdb..#t1') IS NOT NULL 
          DROP TABLE #t1;

    SELECT TOP 3 * INTO #t1 FROM sys.all_columns ac

    IF OBJECT_ID('tempdb..#t1') IS NOT NULL 
         DROP TABLE #t1;

    SELECT TOP 3 * INTO #t1 FROM sys.all_objects ao   -- this query prompt the error

你可以做的是

IF OBJECT_ID('tempdb..#t1') IS NOT NULL 
      DROP TABLE #t1;

SELECT TOP 3 * INTO #t1 FROM sys.all_columns ac

IF OBJECT_ID('tempdb..#t2') IS NOT NULL 
     DROP TABLE #t2;

SELECT TOP 3 * INTO #t2 FROM sys.all_objects ao

IF OBJECT_ID('tempdb..#t3') IS NOT NULL 
     DROP TABLE #t3;

SELECT TOP 3 * INTO #t3 FROM sys.all_parameters ap