Sql-server – Incorrect syntax near the keyword ‘Exec’

sql server

Can you please tell me what is wrong in this query? I am trying to write a SQL query to create a table dynamically

DECLARE @SQLString NVARCHAR(MAX)

SET @SQLString =+ 'Create Table' + GETDATE() + '_' + 'Table' + '' + '(' + 'Column1' + ' ' + 'Nvarchar(50)' + 'Null' + ')' +

Exec @SQLString ;

Best Answer

There are multiple issues with your string @SQLString:

  1. You don't require + at the beginning and at the end
  2. A date will not concatenate with a nvarchar without conversion (CAST or CONVERT)
  3. Because your table will contain spaces you need to put the table name in square brackets: [ and ].
  4. You will be better off with exec sp_executesql @SQLString

So your script might work with this:

DECLARE @SQLString NVARCHAR(MAX)
SET @SQLString = 'Create Table [' + CAST(GETDATE() AS NVARCHAR(30))+ '_Table]' + ' (' + 'Column1' + ' ' + 'Nvarchar(50) Null' + ')' 
PRINT @SQLString
-- Exec sp_executesql @SQLString

I'd recommend reading up on the CREATE TABLE statement and on the String Functions. Then carry on to the Data Type Conversion documentation and have a glimpse at the sp_executesql syntax.

Good Luck.