Execute Dynamic SQL commands in SQL Server

In some applications having hard-coded SQL statements is not appealing, because of the dynamic nature of the queries being issued against the database server. Because of this sometimes there is a need to dynamically create a SQL statement on the fly and then run that command. This can be done quite simply from the application perspective where the statement is built on the fly whether you are using ASP.NET , ColdFusion or any other programming language. But how do you do this from within a SQL Server stored procedure? SQL Server offers a few ways of running a dynamically built SQL statement. These ways are: Writing a query with parameters Using EXEC Using sp_executesql Writing a query with parameters This first approach is pretty straightforward if you only need to pass parameters into the WHERE clause of your SQL statement. Let’s say we need to find all records from the Customers table where City = ‘London’. This can be done easily as the following example shows.

Check If Temporary Table Exists

When working with temporary tables in SQL Server, the common conundrum is often determining whether a temp table exists before performing operations on it. In this blog post, we’ll delve into the nuances of checking the existence of temp tables and explore the potential pitfalls and solutions.

The Basics: Local Temp Tables

To check if a local temp table exists, one commonly used approach is:

IF OBJECT_ID('tempdb..#temp') IS NOT NULL
BEGIN
    PRINT '#temp exists!'
END
ELSE
BEGIN
    PRINT '#temp does not exist!'
END

This method utilizes the OBJECT_ID function to verify the existence of the temp table in the tempdb database.

The Undocumented Second Parameter

An alternative way involves an undocumented optional second parameter:

IF OBJECT_ID('tempdb..#temp','u') IS NOT NULL
BEGIN
    PRINT '#temp exists!'
END
ELSE
BEGIN
    PRINT '#temp does not exist!'
END

However, it’s important to note that using 'u' is undocumented, and relying on undocumented features always comes with a level of caution.

Local Temp Table Caveat

Beware of inadvertently checking the local database:

--Don't do this because this checks the local DB and will return does not exist
IF OBJECT_ID('tempdb..#temp','local') IS NOT NULL
BEGIN
    PRINT '#temp exists!'
END
ELSE
BEGIN
    PRINT '#temp does not exist!'
END

This approach may lead to false negatives as it checks the local database, not the tempdb.

Global Temp Tables Unveiled

Let’s now explore global temp tables, denoted by the double pound sign (##). Creating a global temp table involves:

CREATE TABLE ##temp(id INT)
  • Notice the 2 pound signs, that’s how you create a global variable`

To check its existence:

-- Check if it exists
IF OBJECT_ID('tempdb..##temp') IS NOT NULL
BEGIN
    PRINT '##temp exists!'
END
ELSE
BEGIN
    PRINT '##temp does not exist!'
END

Global temp tables persist beyond the scope of the creating session.

Testing the Waters: Multiple Windows

Now, let’s open a new Query Analyzer window (CTRL + N) and run the same code:

`-- Check if it exists
IF OBJECT_ID('tempdb..##temp') IS NOT NULL
BEGIN
    PRINT '##temp exists!'
END
ELSE
BEGIN
    PRINT '##temp does not exist!'
END` 

Surprisingly, it exists! Global temp tables are visible across different Query Analyzer windows.

Recap and Caution

In summary, checking the existence of temp tables involves the judicious use of OBJECT_ID. Local temp tables are session-specific, and the check should be made in the tempdb database. Global temp tables, on the other hand, persist across sessions.

Understanding these nuances ensures accurate checks and prevents potential pitfalls when working with temporary tables in SQL Server. Happy querying!

Comments

dolcy said…
This post was a great help.
Thanks.
Dawn
Manisha Reddy said…
it's a great post. simple basics. But it was so useful. thanks
Joseph said…
This post is great.. Thank you
Madhu said…
Its really helpful, Thanks Man.
Thanks for your support.
AkAs said…
Simple and useful, Great Post!!
Arvin said…
This comment has been removed by the author.
Arvin said…
thanx. very helpful

Popular posts from this blog

Multiple NULL values in a Unique index in SQL

Row To Column