Click here to Skip to main content
15,903,388 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi.... Guys

my problem is following

insert into TargetDatabase.dbo.tblContact

Select * from SourceDatabase.dbo.tblContact


As shown above. i want to insert data of same table into Same table but database is different

I tried follwing
SQL
Create Procedure Demo
@SourceDatabase as  nvarchar(100),
@TargetDatabase as  nvarchar(100)
as 
exec ( 'insert into' +@TargetDatabase+'.dbo.tblContact')
exec('select * from ' +@SourceDatabase+'.dbo.tblContact')

In this code Select Query is working Fine

but while inserting it is throwing error 'Incorrect syntax near tbl Contact.'

Any help is welcome.

Please help.
Posted
Updated 11-Feb-12 2:43am
v2

exec ( 'insert into' +@TargetDatabase+'.dbo.tblContact')
You have not included any columns of the table here. Thus you get the error.

Your query ought to be
'insert into' + @TargetDatabase+'.dbo.tblContact' (columna,columnb...) values (value1,value2)
 
Share this answer
 
Change the "exec" as:
SQL
exec ( 'insert into' +@TargetDatabase+'.dbo.tblContact ' + 
       'select * from ' +@SourceDatabase+'.dbo.tblContact')
 
Share this answer
 
Comments
Varinder Raii 11-Feb-12 9:07am    
Now it is showing 'Incorrect syntax near *'
Varinder Raii 11-Feb-12 9:25am    
Thanku, Thanku, Thanku
You need to make it a single exec statement:
exec ( 'insert into' +@TargetDatabase+'.dbo.tblContact select * from ' +@SourceDatabase+'.dbo.tblContact')
 
Share this answer
 
Comments
Varinder Raii 11-Feb-12 9:08am    
Now it is showing 'Incorrect syntax near *'
Varinder Raii 11-Feb-12 9:25am    
Thanku, Thanku, Thanku

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900