0

I am trying to create dynamic tables with dynamic columns from one database to another using stored procedure. Since i have sequel of queries and conditions i am using it. But facing issue:

Msg 102, Level 15, State 1, Line 1 Incorrect syntax near '('.

Below is the line where i meet error:

Execute( 'USE ' + @DB1+ ';CREATE TABLE DB2.dbo.'+ @TableName + ' AS (SELECT * [email protected].'+@TableName +')' );

thanks in advance!!

3
  • The answer may be in the error message. Can you show the complete script, especially how you are setting the variables Commented Nov 11, 2017 at 14:35
  • i tried running it in query editor then no issues, but in procedure since using 2 database , i am having this issue. If i use - CREATE TABLE DB2.dbo.'+ @TableName + ' AS (SELECT * [email protected].'+@TableName .. this is also not working. i need a solution for this. Commented Nov 11, 2017 at 14:39
  • Can you please update you question rather than adding comments Commented Nov 11, 2017 at 14:41

2 Answers 2

1

In your code, you are using @DB1 (second occurrence) inside text (inside of single quotes), but needs to be outside, so it would be parsed as variable.

Also you need to use "select * into", because "crate table as" works only in Azure SQL DataWarehouse and is not correct syntax in MS SQL.

So correct code would look like that:

Execute( 'USE ' + @DB1+ '; SELECT * INTO DB2.dbo.'+ @TableName + ' FROM ' + @DB1 + '.dbo.' + @TableName +')' );
Sign up to request clarification or add additional context in comments.

6 Comments

Yes,this worked for me. The create statement i was using does not work in sql procedure.I changed as per your help and it worked for me.Thanks
@ankita25 if this solved your problem, please mark my answer as correct with tick on the left side of my reply ;)
Ok I did @shimon893.. Is their anyway in SQL Procedure where we can do it with two servers (instead of using 2 database of same server).?
Yes, it is possible, you musi link those servers so they will have access to each other. Here is documentation on string this up: msdn.microsoft.com/pl-pl/library/ff772782(v=sql.110).aspx
Thankyou very much @shimon893 ...I will implement it..You have good knowledge!!
|
0
Execute( 'USE ' + @DB1+ '; SELECT * INTO DB2.dbo.'+ @TableName + ' FROM ' + @DB1 + '.dbo.' + @TableName +')' );

2 Comments

I think it would be helpful if you added an explanation as to why the original code in the question does not work.
Because the 'create table ' statement i was using does not work in ms- sql procedure.

Your Answer

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.