Check if table exists in SQL Server
Asked Answered
V

30

1433

I would like this to be the ultimate discussion on how to check if a table exists in SQL Server 2000/2005 using SQL Statements.

Here are two possible ways of doing it. Which one is the standard/best way of doing it?

First way:

IF EXISTS (SELECT 1 
           FROM INFORMATION_SCHEMA.TABLES 
           WHERE TABLE_TYPE='BASE TABLE' 
           AND TABLE_NAME='mytablename') 
   SELECT 1 AS res ELSE SELECT 0 AS res;

Second way:

IF OBJECT_ID (N'mytablename', N'U') IS NOT NULL 
   SELECT 1 AS res ELSE SELECT 0 AS res;

MySQL provides the simple

SHOW TABLES LIKE '%tablename%'; 

statement. I am looking for something similar.

Vasilek answered 3/10, 2008 at 16:0 Comment(0)
P
1620

For queries like this it is always best to use an INFORMATION_SCHEMA view. These views are (mostly) standard across many different databases and rarely change from version to version.

To check if a table exists use:

IF (EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                 WHERE TABLE_SCHEMA = 'TheSchema' 
                 AND  TABLE_NAME = 'TheTable'))
BEGIN
    --Do Stuff
END
Polygamy answered 3/10, 2008 at 16:17 Comment(13)
How would you avoid having schema_name in the where clause? The benefit of using object_id() approach is that it defaults to the current schema.John
Given that an object name alone (that is, without a schema) is not guaranteed to be unique, there is no 100% failsafe way to do this. If you are working with a DB that has no naming conflicts across schemas then simply omitting the "TABLE_SCHEMA = 'TheSchema'" will work just fine.Polygamy
To check for a temporary table, we have to query the tempdb database and use a LIKE operator for the table name SELECT * FROM tempdb.INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'TheSchema' AND TABLE_NAME LIKE '#TheTable%'Sinistrocular
The above tempdb INFORMATION_SCHEMA query will return rows for temp tables created on any connection, not just your current connection. This could result in an "if exists, then drop" statement failing.Camion
A response below that uses the OBJECT_ID function does operate correctly regarding per connection temp tables - https://mcmap.net/q/45281/-check-if-table-exists-in-sql-serverCamion
This is all well, but what if in your --Do Stuff you want to select from TheTable? Then the query will fail. So your --Do Stuff needs to be dynamic?Audiometer
@MarcK Why would the select fail? You have simply checked that the table exists before doing something with it. There is no table locking or anything like that occurring here.Polygamy
@Polygamy SQL query compiler will check for the table before running the query and will fail before even starting.Audiometer
This method has problem if the table does exist but has no data.Eloiseloisa
The TABLE_SCHEMA field in the database I am working with is exclusively populated with "dbo". This does not work for me.Quatrain
This answer doesn't care if it's a view or a table. If you need to know if it's really a table you also need to check the column TABLE_TYPE.Harner
FYI: A common mistake made when performing these checks - what I usually see [not just] beginners do is check existence of a table by querying the records in the table (i.e. IF (EXISTS (SELECT * FROM TheTable)) BEGIN --Do Stuff END While the answer query will return correct results 100% of the time, the query above will return a false negative if your table is empty (has 0 records) and should be avoided at all costs! Just another reason why this is a superior query/why you should always query INFORMATION_SCHEMA.TABLES view when checking table existence.Milliemillieme
This may lock the schema dictionary, which sys.table queries do not.Emlynn
R
349

Also note that if for any reason you need to check for a temporary table you can do this:

if OBJECT_ID('tempdb..#test') is not null
 --- temp table exists
Roslynrosmarin answered 28/1, 2010 at 14:50 Comment(2)
Using this method seems to respect the per connection nature of temp tables. The earlier posted INFORMATION_SCHEMA query will return rows regardless of the connection that created the table.Camion
Retuned: ERROR 1305 (42000): FUNCTION table1.OBJECT_ID does not exist on 10.5.17-MariaDB-1:10.5.17+maria~ubu2004.Cardio
Y
309

We always use the OBJECT_ID style for as long as I remember

IF OBJECT_ID('*objectName*', 'U') IS NOT NULL 
Yuhas answered 3/10, 2008 at 16:5 Comment(9)
I believe this would be fast, though not very portable. Information schema views are guaranteed to exist on any DBRMS that supports the standard. Furthermore, plain OBJECT_ID doesn't guarantee the object's a table.Willamina
Thanks Joe, I was wondering why you would use OBJECT_ID vs INFORMATION_SCHEMA.TABLES vs sys.tables. Pointing out that INFORMATION_SCHEMA is part of a standard pretty much answers that question. BTW it's funny, one of our Database experts that I was going to ask this question has the same last name as you, must be a good last name for databases.Yves
@JoePineda: Then you case use OBJECT_ID('TableName', 'U') to guarantee the object is a table.Gamosepalous
@AllonGuralnek so, instead of following a simple and portable standard, add an extra piece of cryptic info?Ania
@DustinFineout: The question was tagged tsql, so portability doesn't apply as much. In general I've encountered very few truly portable codebases and if succinctness is valued then it sure beats writing that IF EXISTS query from the accepted answer over and over. Plus, everything is cryptic until you read the documentation, especially in T-SQL (or any other variant, really).Gamosepalous
@AllonGuralnek not to mention that I doubt the IF EXISTS BEGIN...END is portable anyway.Cobble
@MartinSmith You're correct, I copy pasted the exists statement into Oracle and it didn't work.Personally a 1 line if statement is always going to be my preference...Scotch
This is my preferred answer, and if you can make a function with a more readable name if you're worried you might forget what IF OBJECT_ID('*objectName*', 'U') IS NOT NULL doesDorsy
Odd this answer isn't is shown higher up.Bradytelic
M
203

Please see the below approaches,

Approach 1: Using INFORMATION_SCHEMA.TABLES view

We can write a query like below to check if a Customers Table exists in the current database.

IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = N'Customers')
BEGIN
    PRINT 'Table Exists'
END

Approach 2: Using OBJECT_ID() function

We can use OBJECT_ID() function like below to check if a Customers Table exists in the current database.

IF OBJECT_ID(N'dbo.Customers', N'U') IS NOT NULL
BEGIN
    PRINT 'Table Exists'
END

Approach 3: Using sys.Objects Catalog View

We can use the Sys.Objects catalog view to check the existence of the Table as shown below:

IF EXISTS(SELECT 1 FROM sys.Objects WHERE  Object_id = OBJECT_ID(N'dbo.Customers') AND Type = N'U')
BEGIN
   PRINT 'Table Exists'
END

Approach 4: Using sys.Tables Catalog View

We can use the Sys.Tables catalog view to check the existence of the Table as shown below:

 IF EXISTS(SELECT 1 FROM sys.Tables WHERE  Name = N'Customers' AND Type = N'U')
 BEGIN
      PRINT 'Table Exists'
 END

Approach 5: Avoid Using sys.sysobjects System table

We should avoid using sys.sysobjects System Table directly, direct access to it will be deprecated in some future versions of the Sql Server. As per Microsoft BOL link, Microsoft is suggesting to use the catalog views sys.objects/sys.tables instead of sys.sysobjects system table directly.

  IF EXISTS(SELECT name FROM sys.sysobjects WHERE Name = N'Customers' AND xtype = N'U')
  BEGIN
     PRINT 'Table Exists'
  END

referred from: http://sqlhints.com/2014/04/13/how-to-check-if-a-table-exists-in-sql-server/

Mudfish answered 22/12, 2014 at 12:1 Comment(2)
Remember to adapt most of the above if the table schema needs to be considered (e.g. 'dbo' or similar). That might save problems later if the same table names are created in a different schema.Hereupon
Five ways of doing the same thing, none of them portable with other DB servers. How hard could it be for MS to add CREATE TABLE IF NOT EXISTS ABC...?Felspar
R
41

Looking for a table on a different database:

if exists (select * from MyOtherDatabase.sys.tables where name = 'MyTable')
    print 'Exists'
Reynoso answered 15/3, 2012 at 17:19 Comment(0)
C
36

Just wanted to mention one situation where it would probably be a little easier to use the OBJECT_ID method. The INFORMATION_SCHEMA views are objects under each database-

The information schema views are defined in a special schema named INFORMATION_SCHEMA. This schema is contained in each database.

https://msdn.microsoft.com/en-us/library/ms186778.aspx

Therefore all tables you access using

IF EXISTS (SELECT 1 
           FROM [database].INFORMATION_SCHEMA.TABLES 
           WHERE TABLE_TYPE='BASE TABLE' 
           AND TABLE_NAME='mytablename') 
   SELECT 1 AS res ELSE SELECT 0 AS res;

will only reflect what is in [database]. If you wanted to check if tables in another database exist, without dynamically changing the [database] each time, OBJECT_ID will let you do this out of the box. Ex-

IF OBJECT_ID (N'db1.schema.table1', N'U') IS NOT NULL 
   SELECT 1 AS res ELSE SELECT 0 AS res;

works just as well as

IF OBJECT_ID (N'db2.schema.table1', N'U') IS NOT NULL 
   SELECT 1 AS res ELSE SELECT 0 AS res;

SQL SERVER 2016 Edit:

Starting with 2016, Microsoft simplified the ability to check for non-existent objects prior to dropping, by adding the if exists keywords to drop statements. For example,

drop table if exists mytablename

will do the same thing as OBJECT_ID / INFORMATION_SCHEMA wrappers, in 1 line of code.

https://blogs.msdn.microsoft.com/sqlserverstorageengine/2015/11/03/drop-if-exists-new-thing-in-sql-server-2016/

Correction answered 22/6, 2016 at 17:18 Comment(0)
I
34
IF OBJECT_ID('mytablename') IS NOT NULL 
Innocency answered 22/11, 2013 at 9:59 Comment(0)
P
17

You can use below code

IF (OBJECT_ID('TableName') IS NOT NULL )
BEGIN
  PRINT 'Table Exists'
END
ELSE
BEGIN 
  PRINT 'Table NOT Exists'
END

Or

IF (EXISTS (SELECT * FROM sys.tables WHERE [name] = 'TableName'))
BEGIN
  PRINT 'Table Exists'
END
ELSE
BEGIN 
  PRINT 'Table NOT Exists'
END
Proleg answered 15/9, 2019 at 5:47 Comment(0)
S
16

Using the Information Schema is the SQL Standard way to do it, so it should be used by all databases that support it. See Approach 1 in this answer.

Superheat answered 3/10, 2008 at 16:3 Comment(2)
This should have been a comment.Beverleybeverlie
This answer needs improvement.Professor
U
11
IF EXISTS 
(
    SELECT   * 
    FROM     sys.objects 
    WHERE    object_id = OBJECT_ID(N'[dbo].[Mapping_APCToFANavigator]') 
             AND 
             type in (N'U')
)
BEGIN

    -- Do whatever you need to here.

END

Here in the above code, the table name is Mapping_APCToFANavigator.

Unpaid answered 7/4, 2011 at 10:39 Comment(2)
If you post code, XML or data samples, please highlight those lines in the text editor and click on the "code samples" button ( { } ) on the editor toolbar to nicely format and syntax highlight it!Chef
Note that the access to system tables might be discontinued in future version of SQL Server. Use Schema views instead.Undercharge
T
10

If you need to work on different databases:

DECLARE @Catalog VARCHAR(255)
SET @Catalog = 'MyDatabase'

DECLARE @Schema VARCHAR(255)
SET @Schema = 'dbo'

DECLARE @Table VARCHAR(255)
SET @Table = 'MyTable'

IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES   
    WHERE TABLE_CATALOG = @Catalog 
      AND TABLE_SCHEMA = @Schema 
      AND TABLE_NAME = @Table))
BEGIN
   --do stuff
END
Tartu answered 21/10, 2009 at 14:58 Comment(1)
Are you sure? Information schema on my 2005 box only returns the current catalog.Menagerie
C
7

I know it is an old question but I have found this possibility if you plan to call it often.

create procedure Table_Exists
@tbl varchar(50)
as
return (select count(*) from sysobjects where type = 'U' and name = @tbl)
go
Courcy answered 21/1, 2011 at 15:37 Comment(1)
-1. Pointless having a procedure for this as it is as much code to call and consume the return as simply to do the select. Should use sysname datatype not varchar(50). Shouldn't use deprecated sysobjects view and takes no account of schema.Cobble
K
6

In SQL Server 2000 you can try:

IF EXISTS(SELECT 1 FROM sysobjects WHERE type = 'U' and name = 'MYTABLENAME')
BEGIN
   SELECT 1 AS 'res' 
END
Kilar answered 16/4, 2015 at 13:42 Comment(0)
A
5

Just adding here, for the benefit of developers and fellow DBAs

a script that receives @Tablename as a parameter

(which may or may not contain the schemaname) and returns the info below if the schema.table exists:

the_name                object_id   the_schema  the_table       the_type
[Facts].[FactBackOrder] 758293761   Facts       FactBackOrder   Table

I produced this script to be used inside other scripts every time I need to test whether or not a table or view exists, and when it does, get its object_id to be used for other purposes.

It raises an error when either you passed an empty string, wrong schema name or wrong table name.

this could be inside a procedure and return -1 for example.

As an example, I have a table called "Facts.FactBackOrder" in one of my Data Warehouse databases.

This is how I achieved this:

PRINT 'THE SERVER IS ' + @@SERVERNAME
--select db_name()
PRINT 'THE DATABASE IS ' + db_NAME() 
PRINT ''
GO

SET NOCOUNT ON
GO

--===================================================================================
-- @TableName is the parameter
-- the object we want to deal with (it might be an indexed view or a table)
-- the schema might or might not be specified
-- when not specified it is DBO
--===================================================================================

DECLARE @TableName SYSNAME

SELECT @TableName = 'Facts.FactBackOrder'
--===================================================================================
--===================================================================================
DECLARE @Schema SYSNAME
DECLARE @I INT
DECLARE @Z INT 

SELECT @TableName = LTRIM(RTRIM(@TableName))
SELECT @Z = LEN(@TableName)

IF (@Z = 0) BEGIN

            RAISERROR('Invalid @Tablename passed.',16,1)

END 

SELECT @I = CHARINDEX('.',@TableName )
--SELECT @TableName ,@I

IF @I > 0 BEGIN

        --===================================================================================
        -- a schema and table name have been passed
        -- example Facts.FactBackOrder 
        -- @Schema = Fact
        -- @TableName = FactBackOrder
        --===================================================================================

   SELECT @Schema    = SUBSTRING(@TABLENAME,1,@I-1)
   SELECT @TableName = SUBSTRING(@TABLENAME,@I+1,@Z-@I)



END
ELSE BEGIN

        --===================================================================================
        -- just a table name have been passed
        -- so the schema will be dbo
        -- example Orders
        -- @Schema = dbo
        -- @TableName = Orders
        --===================================================================================

   SELECT @Schema    = 'DBO'     


END

        --===================================================================================
        -- Check whether the @SchemaName is valid in the current database
        --===================================================================================

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.SCHEMATA K WHERE K.[SCHEMA_NAME] = @Schema ) BEGIN

            RAISERROR('Invalid Schema Name.',16,1)

END 

--SELECT @Schema  as [@Schema]
--      ,@TableName as [@TableName]


DECLARE @R1 TABLE (

   THE_NAME SYSNAME
  ,THE_SCHEMA SYSNAME
  ,THE_TABLE SYSNAME
  ,OBJECT_ID INT
  ,THE_TYPE SYSNAME
  ,PRIMARY KEY CLUSTERED (THE_SCHEMA,THE_NAME)

)

;WITH RADHE_01 AS (
SELECT QUOTENAME(SCHEMA_NAME(O.schema_id)) + '.' + QUOTENAME(O.NAME) AS [the_name]
      ,the_schema=SCHEMA_NAME(O.schema_id)
      ,the_table=O.NAME
      ,object_id =o.object_id 
      ,[the_type]= CASE WHEN O.TYPE = 'U' THEN 'Table' ELSE 'View' END 
from sys.objects O
where O.is_ms_shipped = 0
AND O.TYPE IN ('U','V')
)
INSERT INTO @R1 (
   THE_NAME 
  ,THE_SCHEMA 
  ,THE_TABLE 
  ,OBJECT_ID
  ,THE_TYPE 
)
SELECT  the_name
       ,the_schema
       ,the_table
       ,object_id
       ,the_type
FROM RADHE_01
WHERE the_schema = @Schema 
  AND the_table  = @TableName

IF (@@ROWCOUNT = 0) BEGIN 

             RAISERROR('Invalid Table Name.',16,1)

END 
ELSE BEGIN

    SELECT     THE_NAME 
              ,THE_SCHEMA 
              ,THE_TABLE 
              ,OBJECT_ID
              ,THE_TYPE 

    FROM @R1

END 
Acronym answered 23/1, 2015 at 17:40 Comment(2)
There are a lot of assumptions in your script. For instance, I could easily craete a table named dbo.[hello.world ] and the script would not find it for multiple reasons. That said, it's unlikely anyone would want to create such a table, but still. Anyway, your THE_NAME column is defined as sysname', yet you try to squeeze 2 sysname` columns and a dot (.), all surrounded in square brackets in there... that one is bound to fail someday!Lightproof
@Lightproof I agree sysname is not the best data type to be used, yet the script has been running for a long time without any errors, I would spend time on it only if I find a reasonable situation where it does not work. Even better, you take this code, improve it and post it here as an answer and I will test it, if it works I will upvote your answer.Acronym
K
4
IF EXISTS 
(
    SELECT  * 

    FROM    INFORMATION_SCHEMA.TABLES 

    WHERE   TABLE_SCHEMA = 'PutSchemaHere'     
            AND  
            TABLE_NAME   = 'PutTableNameHere'
)
Kalidasa answered 24/10, 2013 at 11:4 Comment(0)
N
3

I think the following query works:

IF EXISTS (select * from sys.tables 
WHERE name='mytablename' )
BEGIN
     print 'table exists in the database'
END
Noetic answered 3/10, 2022 at 12:36 Comment(0)
H
2

You can use this :

     IF OBJECT_ID (N'dbo.T', N'U') IS NOT NULL 
        BEGIN 
            print 'deleted table';
            drop table t 
        END
     else 
        begin 
            print 'table not found' 
        end

 Create table t (id int identity(1,1) not null, name varchar(30) not null, lastname varchar(25) null)
 insert into t( name, lastname) values('john','doe');
 insert into t( name, lastname) values('rose',NULL);

 Select * from t
1   john    doe
2   rose    NULL

 -- clean
 drop table t
Hooded answered 18/11, 2014 at 14:36 Comment(0)
P
2

I've had some problems either with selecting from INFORMATIONAL_SCHEME and OBJECT_ID. I don't know if it's an issue of ODBC driver or something.. Queries from SQL management studio, both, were okay.

Here is the solution:

SELECT COUNT(*) FROM <yourTableNameHere>

So, if the query fails, there is, probably, no such table in the database (or you don't have access permissions to it).

The check is done by comparing the value (integer in my case) returned by SQL executor which deals with ODBC driver..

if (sqlexec(conectionHandle, 'SELECT COUNT(*) FROM myTable') == -1) {
  // myTable doesn't exist..
}
Pariah answered 22/3, 2019 at 5:31 Comment(4)
Fails with what output?Zales
@wscourge, SQL query failed or something alike. I just check the return value from the executor function.Pariah
Add it to your answerZales
Using FireDac you get an exception if the table doesn't exist, nice and simple. Yeah, I know, not TSQL, welcome to the real world.Importunacy
E
2
IF EXISTS (
SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE 
TABLE_CATALOG = 'Database Name' and
TABLE_NAME = 'Table Name' and 
TABLE_SCHEMA = 'Schema Name') -- Database and Schema name in where statement can be deleted

BEGIN
--TABLE EXISTS
END

ELSE BEGIN
--TABLE DOES NOT EXISTS
END
Ejaculatory answered 3/7, 2019 at 10:3 Comment(0)
M
1

Something important to know for anybody who hasn't found their solution yet: SQL server != MYSQL. If you want to do it with MYSQL, it is quite simple

    $sql = "SELECT 1 FROM `db_name`.`table_name` LIMIT 1;";
    $result = mysql_query($sql);
    if( $result == false )
        echo "table DOES NOT EXIST";
    else
        echo "table exists";

Posting this here because it's the top hit at Google.

Mayfield answered 23/7, 2014 at 13:55 Comment(2)
-1 because the OP is precisely asking for a SQL Server solution to the problem, not the MySQL one. He wrote about MySQL because he knew the solution on that DBMS and he wanted the same result on SQL Server. Also your answer is not even a MySQL query, but a PHP code that works with MySQL.Adobe
@mordack550, I agree with Blauhirn. He's right. This is the top hit on Google for finding out if a table exists in SQL. He's intentions are good and his information is helpful. +1Howdy
S
1
IF EXISTS (   SELECT * FROM   dbo.sysobjects WHERE  id = OBJECT_ID(N'dbo.TableName') AND OBJECTPROPERTY(id, N'IsUserTable') = 1 )
BEGIN
  SELECT * FROM dbo.TableName;
END
GO
Stroh answered 19/6, 2018 at 8:54 Comment(0)
A
1

There is one more option to check if the table exists across databases

IF EXISTS(SELECT 1 FROM [change-to-your-database].SYS.TABLES WHERE NAME = 'change-to-your-table-name')
BEGIN
    -- do whatever you want
END
Amie answered 27/2, 2020 at 5:18 Comment(0)
B
0

If anyone is trying to do this same thing in linq to sql (or especially linqpad) turn on option to include system tables and views and do this code:

let oSchema = sys.Schemas.FirstOrDefault(s=>s.Name==a.schema )
where oSchema !=null
let o=oSchema!=null?sys.Objects.FirstOrDefault (o => o.Name==a.item && o.Schema_id==oSchema.Schema_id):null
where o!=null

given that you have an object with the name in a property called item, and the schema in a property called schema where the source variable name is a

Bandaranaike answered 7/2, 2014 at 18:48 Comment(0)
M
0
select name from SysObjects where xType='U' and name like '%xxx%' order by name
Main answered 10/2, 2014 at 18:54 Comment(0)
M
0

If this is to be the 'ultimate' discussion, then it should be noted that Larry Leonard's script can query a remote server as well if the servers are linked.

if exists (select * from REMOTE_SERVER.MyOtherDatabase.sys.tables where name = 'MyTable')
    print 'Exists'
Montalvo answered 18/8, 2014 at 22:8 Comment(1)
Perhaps it's more suited to add this as a comment to Leonards answer or maybe as an edit?Brockway
A
0

-- -- create procedure to check if a table exists


DELIMITER $$

DROP PROCEDURE IF EXISTS `checkIfTableExists`;

CREATE PROCEDURE checkIfTableExists(
    IN databaseName CHAR(255),
    IN tableName CHAR(255),
    OUT boolExistsOrNot CHAR(40)
)

  BEGIN
      SELECT count(*) INTO boolExistsOrNot FROM information_schema.TABLES
      WHERE (TABLE_SCHEMA = databaseName)
      AND (TABLE_NAME = tableName);
  END $$

DELIMITER ;

-- -- how to use : check if table migrations exists


 CALL checkIfTableExists('muDbName', 'migrations', @output);
Admass answered 6/9, 2017 at 9:39 Comment(0)
K
0

i taking here creating a view as example.

Because ALTER/CREATE commands can't be within BEGIN/END blocks. You need to test for existence and the drop it before doing a create

IF Object_ID('TestView') IS NOT NULL
DROP VIEW TestView

GO

CREATE VIEW TestView
   as
   . . .

GO

If you are woried about the permissions being lost you can script the GRANT statements as well and re-run those at the end.

You could wrap the create/alter into a string and do an EXEC - that might get ugly for large views

DECLARE @SQL as varchar(4000)

-- set to body of view
SET @SQL = 'SELECT X, Y, Z FROM TABLE' 

IF Object_ID('TestView') IS NULL
    SET @SQL = 'CREATE VIEW TestView AS ' + @SQL
ELSE    
    SET @SQL = 'ALTER VIEW TestView AS ' + @SQL
Kyanite answered 6/1, 2020 at 8:22 Comment(0)
T
0

why most of user say 'if *** is not null' !?, try 'if *** is null' :)

IF OBJECT_ID(N'[dbo].[Error]', N'U') IS null
BEGIN
    CREATE TABLE [dbo].[Error](
        [id] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY,
        [Values] [nvarchar](MAX) NOT NULL,
        [Created] [datetimeoffset](0) NOT NULL,
        )
END
Tatiana answered 23/5, 2023 at 8:17 Comment(0)
P
-2

Run this query to check if the table exists in the database:

IF(SELECT TABLE_NAME from INFORMATION_SCHEMA.TABLES where TABLE_NAME = 'YourTableName') IS NOT NULL
PRINT 'Table Exists';
Peal answered 29/5, 2019 at 13:38 Comment(1)
This query may fail because the schema is not checked, which may cause more than one result to be returned. Adding a TABLE_SCHEMA condition will resolve this issue.Rumph
A
-5

consider in one database you have a table t1. you want to run script on other Database like - if t1 exist then do nothing else create t1. To do this open visual studio and do the following:

Right click on t1, then Script table as, then DROP and Create To, then New Query Editor

you will find your desired query. But before executing that script don't forget to comment out the drop statement in the query as you don't want to create new one if there is already one.

Thanks

Astrea answered 10/4, 2013 at 18:32 Comment(2)
In SSMS 2012 it no longer performs the if-exists check, if it ever did it (I do not remember how former versions generated the above script). Maybe you are mistaken with the way other db tools are scripting table objects?Seldan
SSMS will perform the if-exists check if you ask it to. Tools > Options > SQL Server Object Explorer > Scripting > "Object scripting options": "Check for object existence" = TrueWallah

© 2022 - 2024 — McMap. All rights reserved.