Come determinare se una tabella temporanea esiste in SQL Server

June 16

Come determinare se una tabella temporanea esiste in SQL Server


Quando si scrive una stored procedure per SQL Server, a volte è utile essere in grado di scoprire se una tabella temporanea esiste già. Ad esempio, quando si tenta di creare una tabella, ma una tabella esiste già, si verificano errori. Verificare la presenza di una tabella temporanea con alcuni semplici comandi.

istruzione

1 Utilizzare la funzione OBJECT_ID a cercare per la vostra tavola. Questa funzione restituisce il numero di identificazione interno di un oggetto di database. Si può usare per trovare una tabella temporanea con il suo vero nome. Ad esempio, fare riferimento al seguente codice.

SELEZIONARE OBJECT_ID ( 'tempdb .. # TemporaryTable')

2 Combinare OBJECT_ID con e IF ... ELSE per eseguire codice diverso a seconda se non la nostra tabella temporanea esiste già. Per esempio -
SE OBJECT_ID ( 'tempdb .. # TemporaryTable') non è NULL

PRINT 'The temporary table already exists!'

ALTRO

PRINT 'The temporary table does not exist!'

3 Salvare ed eseguire il programma. L'output del comando OBJECT_ID ti dice se una tabella temporanea esiste.

Consigli e avvertenze

  • Questo funziona in SQL Server 2000, 2005 e 2008. Non sono sicuro circa le versioni precedenti.