Problem solve Get help with specific problems with your technologies, process and projects.

Copying SQL Server database tables

SQL Server expert Greg Low explains how to copy tables from one database into another.

I am executing a stored procedure, 'test', in a database called db1. Within this stored procedure, I want to check if db2 database exists. If it does not exist, I want to create the db2 and then copy tables from db1 into db2.

Code: --in db1 context IF EXISTS (SELECT name FROM sysobjects WHERE name = 'test' AND type = 'P') DROP PROCEDURE dbo.test GO

CREATE PROCEDURE dbo.test AS --to create db if not existing IF NOT EXISTS (select name from [master].dbo.sysdatabases where name = 'db2') CREATE DATABASE db2 /* if tabl1 exists in db1 then it is copied into db2 and dropped frm db1 */ IF EXISTS (SELECT name FROM sysobjects WHERE name = 'tabl1' and xtype='U') BEGIN SELECT * INTO [db2].dbo.tabl1 FROM tabl1 DROP TABLE tabl1 print 'dropped table' END

When I try to execute this, I get the following error msg:

Server: Msg 2702, Level 16, State 2, Procedure test, Line 10 Database 'db2' does not exist.

How do I get this working?

You'll need to restructure this so one procedure creates the database if necessary and the next procedure called does the real work.

View questions and answers from all of our SQL Server experts here.

Dig Deeper on SQL Server Stored Procedures

Start the conversation

Send me notifications when other members comment.

Please create a username to comment.