Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to get a database object based on an OBJECT_ID?
    primarykey
    data
    text
    <p>In SQL Server 2008, is there a way to access an object based on the <code>OBJECT_ID</code>?</p> <p>[Edit] The example described below was solved using Andrew's suggestion in the comment, but I'm still curious about the general case. Can an object itself be retrieved using <code>OBJECT_ID</code>, or can it only be accessed indirectly by using the object name via <code>sp_executesql</code>?</p> <p>My specific case is a stored procedure that uses several temporary tables. At the end of the procedure I want to dump the data from the temporary tables into actual tables for analysis (only if a debug switch is enabled).</p> <p>The code for dumping the data is similar to this:</p> <pre><code>IF OBJECT_ID('tempdb..#MyTempTable', 'U') IS NOT NULL BEGIN IF OBJECT_ID('Debug_MyTempTable', 'U') IS NOT NULL DROP TABLE Debug_MyTempTable SELECT * INTO Debug_MyTempTable FROM #MyTempTable END </code></pre> <p>This code block is repeated for each temporary table, so I would prefer to put it in a procedure and call it with a table name:</p> <pre><code>EXEC [dbo].[CreateDebugTable] @tableName = 'MyTempTable' </code></pre> <p>I imagine the procedure would look something like:</p> <pre><code>CREATE PROCEDURE [dbo].[CreateDebugTable] @tableName VARCHAR(50) AS BEGIN IF OBJECT_ID('tempdb..#' + @tableName, 'U') IS NOT NULL BEGIN IF OBJECT_ID('dbo.Debug_' + @tableName, 'U') IS NOT NULL DROP TABLE &lt;Debug_TempTable&gt; SELECT * INTO &lt;Debug_TempTable&gt; FROM &lt;#TempTable&gt; END END </code></pre> <p>The procedure depends on being able to translate the <code>OBJECT_ID</code> of <code>DebugTempTable</code> and <code>#TempTable</code> into the actual tables (shown with &lt;> in the code above). Is this possible?</p> <p>[Edit] This is the altered procedure using <code>sp_executesql</code> instead of explicit tables.</p> <pre><code>CREATE PROCEDURE [dbo].[CreateDebugTable] @tableName VARCHAR(50) AS BEGIN DECLARE @tmpTable VARCHAR(50) = '#' + @tableName DECLARE @dboTable VARCHAR(50) = 'Debug_' + @tableName DECLARE @sql NVARCHAR(100) IF OBJECT_ID('tempdb..' + @tmpTable, 'U') IS NOT NULL BEGIN IF OBJECT_ID('dbo.' + @dboTable, 'U') IS NOT NULL BEGIN SET @sql = 'DROP TABLE ' + @dboTable EXECUTE sp_executesql @sql END SET @sql = 'SELECT * INTO ' + @dboTable + ' FROM ' + @tmpTable EXECUTE sp_executesql @sql END END </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload