SQL Server Using dynamic SQL to Create Table with today’s date as the table name

tkclm6bt  于 2023-11-16  发布在  其他
关注(0)|答案(1)|浏览(132)

I am attempting to create a table where the name of the table is todays date and the time of day in the format 2023-11-06-12-10. My code looked like this and errored with the message "Incorrect syntax near '2023'".

DECLARE @MyTableName sysname;
DECLARE @DynamicSQL nvarchar(max);
SET @MyTableName = FORMAT (GETDATE(), 'yyyy-MM-dd-hh-mm');
SET @DynamicSQL = N'CREATE TABLE ' + @MyTableName + ' (DocIDNo varchar(255))';
EXEC sp_executesql @DynamicSQL;

I changed the SET @MyTableName to this

SET @MyTableName = 'House'

and this worked :) I then tried

SET @MyTableName = '2023'

and got the same error "Incorrect syntax near '2023'"

icnyk63a

icnyk63a1#

As @AlwaysLearning mentioned you can try using the QUOTENAME function to ensure that the table name is properly quoted and any special characters are handled correctly:

DECLARE @MyTableName sysname;
DECLARE @DynamicSQL nvarchar(max);
SET @MyTableName = REPLACE(FORMAT(GETDATE(), 'yyyy-MM-dd-hh-mm'), ' ', '_');
SET @DynamicSQL = N'CREATE TABLE ' + QUOTENAME(@MyTableName) + ' (DocIDNo varchar(255))';
EXEC sp_executesql @DynamicSQL;

相关问题