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?