CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Nov 2000
    Posts
    70

    T-SQL code to check if a table exists in SQL Server


    Hi,

    I want to check if a table exists within a SQL Server trigger, which means I have to do it in T-SQL. Does anyone know if it is possible to do this, and if so, how? If it cannot be done explicitly, there must be some way to catch the resulting exception and then create the table. How would that be done?

    Thank you for your help.



  2. #2
    Join Date
    Apr 2001
    Location
    The Netherlands
    Posts
    1

    Re: T-SQL code to check if a table exists in SQL Server

    Hi,

    I think this is what you are looking for:

    if exists (select * from sysobjects where id = object_id(N'[dbo].[tbl_Age_class]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[tbl_Age_class]
    GO

    CREATE TABLE [dbo].[tbl_Age_class] (
    [Country_code] [varchar] (3) NOT NULL ,
    [Age_class_code] [varchar] (5) NOT NULL ,
    [Year] [int] NOT NULL ,
    [Age_class_descr] [varchar] (50) NULL
    ) ON [PRIMARY]
    GO

    This script checks to see if tbl_Age_Class exists, if it does drops it and then recreates it.

    I created this script by right clicking the mouse over the table and then select all tasks/generate SQL-script.

    Good luck


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured