0

I am trying to create a table dynamically depending upon current date in SQL Server. But I am unable to do so. I am getting error as invalid identifier.

These are the details:

SQL query:

DECLARE @tableToDump nvarchar(100); 
SET @tableToDump = 'backupCdc'+cast(cast(GETDATE() as date) as char(100));
DECLARE @DynamicSQL nvarchar(1000);
SET @DynamicSQL=N'create table '+ @tableToDump +' ('+'cid int primary key AUTO_INCREMENT, employeeno Varchar(100), fieldName Varchar(100) NOT NULL, fieldValue Varchar(1000))';
exec @DynamicSQL;

Output (error):

The name 'create table backupCdc2015-09-10 (cid int primary key AUTO_INCREMENT, employeeno Varchar(100), fieldName Varchar(100) NOT NULL, fieldValue Varchar(1000))' is not a valid identifier.

marc_s
9,0626 gold badges46 silver badges52 bronze badges
asked Sep 10, 2015 at 9:04
2
  • 1
    I think you need exec (@DynamicSQL); Otherwise SQL-Server tries to find a stored procedure with the name 'create table ...' Commented Sep 10, 2015 at 9:32
  • Be careful to assure yourself that creating many tables like this is a good idea - it is a pattern that can be a pain to maintain and report upon (the book "SQL Anitpatterms" covers it and the problems it can cause in the chapter "metadata tribbles". If you are doing this for performance reasons and have access to Enterprise Edition then consider using the built-in support for table partitioning instead. Commented Sep 10, 2015 at 13:08

1 Answer 1

0

You can try with different format of date. I also changed AUTO_INCREMENT to Identity

DECLARE @tableToDump nvarchar(100); 
SET @tableToDump = 'backupCdc'+CONVERT(varchar(10),getdate(),112);
DECLARE @DynamicSQL nvarchar(1000);
SET @DynamicSQL=N'create table '+ @tableToDump +' ('+'cid int primary key IDENTITY(1,1), employeeno Varchar(100), fieldName Varchar(100) NOT NULL, fieldValue Varchar(1000))';
/*Adding braces is important as suggested by ypercube */
exec (@DynamicSQL);
code chimp
71 gold badge1 silver badge3 bronze badges
answered Sep 10, 2015 at 9:23
2
  • No luck. I also changed it as - SET @tableToDump = 'backupCdc'; Commented Sep 10, 2015 at 9:29
  • Print your Dynamic SQL insstead of executing and try to find out whats going wrong as it worked on my machine. Commented Sep 10, 2015 at 9:35

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.