Click to See Complete Forum and Search --> : T-SQL code to check if a table exists in SQL Server


ssukumar
April 25th, 2001, 04:35 PM
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.

bluffert
April 26th, 2001, 04:23 AM
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