Link to home
Start Free TrialLog in
Avatar of McGurk1
McGurk1Flag for United States of America

asked on

TSQL determine if a table exists

How do I determine if a table exists using TSQL?
Avatar of tigin44
tigin44
Flag of Türkiye image

this checks if a table exists

IF EXISTS (SELECT NULL FROM sys.sysobjects WHERE name = N'tableName')
ASKER CERTIFIED SOLUTION
Avatar of Saurabh Bhadauria
Saurabh Bhadauria
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
IF EXISTS (SELECT * FROM sys.sysobjects WHERE name = N'tableName')
Avatar of McGurk1

ASKER

IF EXISTS (SELECT NULL FROM sys.sysobjects WHERE name = 'mytablename')
BEGIN
select * from mytablename
END

This completes successfully but doesn't give me any records.   Running the select clause alone gives me the records I need.  What is the difference?
IF EXISTS (SELECT id FROM sys.sysobjects WHERE name = 'mytablename')
BEGIN
select * from mytablename
END
Avatar of Aneesh
you MUST include the object owner/ Schema, without that, can get you wrong result

if object_id(' schemaname.TableName') is not null
      select 'table exists'
Avatar of McGurk1

ASKER

All checked for the table but Saurv's solution also produced the records.