1

I'm a little confused on the code that is being suggested for checking if a table exists. Can someone explain whether the code that I have written will work for checking if a table exists?

I want it to do nothing if the table does exist.

Here is my code:

BEGIN 
SET NOCOUNT ON;

DECLARE @SQL NVARCHAR(MAX);

IF NOT EXISTS (SELECT * FROM sys.objects
WHERE object_id = OBJECT_ID(N' + @TABLENAME + ') AND type in (N'U'))

    BEGIN
        SET @SQL = 

        N'CREATE TABLE ' + @TABLENAME + '
        ('
        + '[ID] [int] IDENTITY(1,1) NOT NULL,
        [intID] [int] NULL,
        [varID] [varchar](50) NULL,
        [FormName] [varchar](250) NULL,
        [UID] [varchar](3) NOT NULL,
        CONSTRAINT [PK_Selections' + @TABLENAME + '_1] PRIMARY KEY CLUSTERED(
        [ID]));';

        EXEC sp_executesql @sql;
    END


END

I forgot to mention that currently the procedure DOES create the table. But when I run the procedure again it tries to create the table again and then fails.

How do I make it exit the procedure if the table exists?

3 Answers 3

7

Just do this simple check. No need to query sys.objects

...    
IF OBJECT_ID(@TABLENAME, 'U') IS NULL
BEGIN

Your check failed because you were actually looking for a table called "+ @TABLENAME +"

Sign up to request clarification or add additional context in comments.

1 Comment

Can you briefly explain why I wouldn't use the other method just so I understand further please
1

Here is the checking whether table exists or not:

IF NOT EXISTS (SELECT * FROM sys.objects
WHERE object_id = OBJECT_ID(N' + @TABLENAME + ') AND type in (N'U'))

table sys.objects contains description all objects in a database.

Function OBJECT_ID() - return id of object by its name.

type in (N'U')) - checks that object was created by user.

To check that table is EXISTS use check:

IF EXISTS (SELECT * FROM sys.objects
WHERE object_id = OBJECT_ID(N' + @TABLENAME + ') AND type in (N'U'))
BEGIN
...
END

1 Comment

The code is wrong, no matter how you explain it... The question mentions this at the end when it keeps trying to create the table
1

Try this:

IF NOT EXISTS(SELECT TABLE_NAME from INFORMATION_SCHEMA.TABLES WHERE
 TABLE_NAME=LTRIM(RTRIM(@TABLENAME )) AND TABLE_TYPE='BASE TABLE'

BEGIN
  -- CREATE YOUR TABLE
END

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.