How to retrieve field names from temporary table (SQL Server 2008)
Fetch column names of a SQL Server temp table with this snippet:
In the above snippet, replace #TempTable
with the name of your actual temporary table. It directly fetches column names from tempdb, which is the residence for temporary tables.
Nuts and bolts: Basics and Beyond
A table without details about its columns is just like a whisper in the wind. So, let's fetch more context than just names using join between tempdb.sys.columns and tempdb.sys.types:
With the above snippet, you'll end up with more than just column names. You'll also have details about the data types, nullability, and more!
Finding Dory or the object_id
To get the correct object_id of a temporary table, use:
Remember, if your temporary table starts with single hash (#), it's session-specific, so object_id will vary accordingly. double hash (#) indicates global visibility.
INFORMATION_SCHEMA.COLUMNS
can be a safe friend when the going gets tough to write the deeply rooted schema-bound code.
Attention: Collisions ahead
In multi-user environments, remember the risk of session collisions, as distinct users may create temp tables with identical names leading to unexpected results. To avoid head-on collisions, appending the session-specific suffix to the table query is the seatbelt of your code!
Taking a ride on the stored procedures
For a more versatile tool, try SQL Server stored procedure sp_columns for fetching column details of a temporary table:
This command wraps up the tough logic and you won't need to join system tables or bother about catching the elusive object_id
.
Furthering your exploration
If your playground gets bigger and complex, where dynamic SQL generation or creating utility procedures are the talk of the town, don't hesitate to write a T-SQL function that bundles up this logic preventing potential bugs and enhancing readability of your code.
Was this article helpful?