0

I'm using Azure SQL Database (T-SQL), and having problems with a "CREATE TABLE IF NOT EXISTS" query. I've already read the links here, and probably a few others:

My code:

declare @tableName nvarchar(max);
declare @sqlquery nvarchar(max);
SET @tableName = 'Russ';
SET @sqlquery = 'if not exists (select * from sysobjects where name=' + @tableName + 'and xtype=''U'') create table ' + @tableName + '([ID] [bigint] PRIMARY KEY NOT NULL DEFAULT (NEXT VALUE FOR dbo.standardsequence), [Name One] [nvarchar](64) NOT NULL, [Name Two] [nvarchar](64) NOT NULL)';
exec sp_executesql @sqlquery;
  • Error I'm getting is "Syntax error near xtype='U'", but I've escaped that part so I don't understand the problem there.
  • Every place says to use sp_executesql, which I'm doing. I also tried setting the variable in the sp_executesql statement (ex: EXECUTE sp_executesql @SQL, N'@tableName VARCHAR(10)', 'Russ'), but it doesn't work that way either.
  • Query works perfectly fine without variables, so I'm pretty sure the problem is with that, but just don't know why.

What am I doing wrong? I am stumped. If there was a Stumped Bureau, they'd declare me officially stumped.

Netside
  • 70
  • 1
  • 9
  • Please remove `if not exists (select * from sysobjects where name=' + @tableName + 'and xtype=''U'') create table ' + @tableName + '([ID] [bigint] PRIMARY KEY NOT NULL DEFAULT (NEXT VALUE FOR dbo.standardsequence), [Name One] [nvarchar](64) NOT NULL, [Name Two] [nvarchar](64) NOT NULL)` in your query `xtype` to `type` – jishan siddique Oct 23 '19 at 04:30
  • You can't use PRINT in Azure SQL editor, just FYI. Probably wouldn't have had a problem if I could. – Netside Oct 23 '19 at 04:47
  • Thanks, man for sharing the knowledge :) – jishan siddique Oct 23 '19 at 04:56
  • @jishansiddique I didn't see what you said a few days ago, but this makes me curious and interested - Why change "xtype" to just "type"? This didn't solve my problem, but just curious. – Netside Oct 28 '19 at 05:59

1 Answers1

2

table name is not properly terminated, additional quotes will fix it.

but, its a good practice to add begin and end when using conditional statements in sql

declare @tableName nvarchar(max);
declare @sqlquery nvarchar(max);
SET @tableName = 'Russ';
SET @sqlquery = 'if not exists (select * from sysobjects where name=''' + @tableName + ''' and xtype=''U'') 
    begin 
        create table ' + @tableName + '([ID] [bigint] PRIMARY KEY NOT NULL DEFAULT (NEXT VALUE FOR dbo.standardsequence), [Name One] [nvarchar](64) NOT NULL, [Name Two] [nvarchar](64) NOT NULL) 
    end';

exec sp_executesql @sqlquery;
Ed Bangga
  • 11,622
  • 4
  • 10
  • 29