Why does SQL Server thinks a Temp Table already exists when it doesn't?

后端 未结 4 886
挽巷
挽巷 2020-12-20 15:54

Background: There\'s a stored procedure which does \"stuff\" with a temp table of a given name. The procedure is generic in that it inspects the schema of the temp table and

相关标签:
4条回答
  • 2020-12-20 16:43

    Instead of #test, use a fully qualified name. For example,

    [tempdb].[dbo].[temptable]
    

    I learned this little trick here Insert result of executing dynamic query into a table .

    Intellisense will complain but you will still be able to create or alter the stored procedure.

    When done with it, be sure to drop it:

    DROP TABLE [tempdb].[dbo].[temptable]
    
    0 讨论(0)
  • 2020-12-20 16:47

    It's a limitation. Dynamic SQL won't work either since #tmp will be created in a new session and immediately lost. For the EXACT snippet as shown, this does the same

    CREATE TABLE #test
    (
        a BIGINT NOT NULL,
        b BIGINT NOT NULL
    )
    
    IF not (1=1)
        ALTER TABLE #test ADD c BIGINT NOT NULL   
    

    There cannot be two CREATE .. #name within the same batch, but this will also work in general form

    IF (1=1)
    BEGIN
        CREATE TABLE #test
        (
            a BIGINT NOT NULL,
            b BIGINT NOT NULL
        );
    END 
    GO
    
    IF NOT (1=1)
    BEGIN
        CREATE TABLE #test
        (
            a BIGINT NOT NULL,
            b BIGINT NOT NULL,
            c BIGINT NOT NULL   
        )
    END
    
    0 讨论(0)
  • 2020-12-20 16:49

    since i dont have sql 2008, i cannot test it. however as far as i know, this is a parser issue explicitly with temp tables. the same would work fine with normal tables

    to sort this out, just split your code with logical GO statements

    ideally: check for existence of temp tables before you create your temp tables, drop them if they exist, fire a go, do the creation of temp tables again, fire a go, then any post processing, fire a go, finally drop them again and fire the last go


    you might also want to try and use the table variable instead of temp tables if above does not solve it for you

    0 讨论(0)
  • 2020-12-20 16:50

    You could always "cheat":

    DECLARE @SQL VARCHAR(200)
    
    IF (1=1)
    BEGIN
        SET @SQL = 'CREATE TABLE #Temp     ' +
                   '(                      ' +
                   '    a BIGINT NOT NULL, ' +
                   '    b BIGINT NOT NULL  ' +
                   ')                      '
    END
    ELSE
    BEGIN
        SET @SQL = 'CREATE TABLE #Temp     ' +
                   '(                      ' +
                   '    a BIGINT NOT NULL, ' +
                   '    b BIGINT NOT NULL, ' +
                   '    c BIGINT NOT NULL  ' +
                   ')                      '
    END
    
    EXEC SP_EXECUTESQL @SQL
    
    0 讨论(0)
提交回复
热议问题