title: If table exists with dynamic query in SQL Server
body: <p>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?</p>
  
  <p>I want it to do nothing if the table does exist.</p>
  
  <p>Here is my code:</p>
  
  <pre><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
  </code></pre>
  
  <p>I forgot to mention that currently the procedure <strong>DOES</strong> create the table. But when I run the procedure again it tries to create the table again and then fails.</p>
  
  <p>How do I make it exit the procedure if the table exists?</p>