Search code examples
sqlsql-serversql-server-2014

Check if a temp table exists when I only know part of the name?


I have a function for checking if certain tables exist in my database, using part of the table name as a key to match (my table naming conventions include unique table name prefixes). It uses a select statement as below, where @TablePrefix is a parameter to the function and contains the first few characters of the table name:

DECLARE @R bit;

    SELECT @R = COUNT(X.X)
        FROM ( 
          SELECT TOP(1) 1 X FROM sys.tables WHERE [name] LIKE @TablePrefix + '%' 
        ) AS X;
    
RETURN @R;

My question is, how can I extend this function to work for #temp tables too?

I have tried checking the first char of the name for # then using the same logic to select from tempdb.sys.tables, but this seems to have a fatal flaw - it returns a positive result when any temp table exists with a matching name, even if not created by the current session - and even if created by SPs in a different database. There does not seem to be any straightforward way to narrow the selection down to only those temp tables that exist in the context of the current session.

I cannot use the other method that seems universally to be suggested for checking temp tables - IF OBJECT('tempdb..#temp1') IS NOT NULL - because that requires me to know the full name of the table, not just a prefix.


Solution

  • create table #abc(id bit);
    create table #abc_(id bit);
    create table #def__(id bit);
    create table #xyz___________(id bit);
    go
    
    select distinct (left(t.name, n.r)) as tblname
    from tempdb.sys.tables as t with(nolock)
    cross join  (select top(116) row_number() over(order by(select null)) as r from sys.all_objects with(nolock)) as n
    where t.name like '#%'
    and object_id('tempdb..'+left(t.name, n.r)) is not null;
    
    
    drop table #abc;
    drop table #abc_;
    drop table #def__;
    drop table #xyz___________;