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'"
1条答案
按热度按时间icnyk63a1#
As
@AlwaysLearning
mentioned you can try using theQUOTENAME
function to ensure that the table name is properly quoted and any special characters are handled correctly: