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

后端 未结 4 891
挽巷
挽巷 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: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
    

提交回复
热议问题