Change database dynamically in SQL Server using a stored procedure

I have a question about SQL Server: how to change database name dynamically and use one select and insert statment to load data using a stored procedure.

How to change the database name with insert and select statement while table data loading into another table?

Here each database name related table load into with in the database name related target table.

ie database: test and source table: emp target table is :emptarget here emp table records load into emptarget similar to another databases

Database names information maintain one table.

USE [test]
GO

CREATE TABLE [dbo].[databaseinformation]
(
    [id] [int] NULL,
    [databasename] [varchar](50) NULL
) ON [PRIMARY]
GO

INSERT [dbo].[databaseinformation] ([id], [databasename]) 
VALUES (1, N'test'), (2, N'test1')
GO

Table1 : source : emp and datbasename: test

USE [test]
CREATE TABLE [dbo].[emp]
(
    [id] [int] NULL,
    [name] [varchar](50) NULL,
    [sal] [int] NULL
) 

INSERT [dbo].[emp] ([id], [name], [sal]) 
VALUES (19, N'hd', 40), (1, N'g', 10),
       (9, N'dk', 90), (80, N'dhe', 80)
GO

Target table : emptarget and databasename: test

USE [test]
CREATE TABLE [dbo].[emptarget]
(
    [id] [int] NULL,
    [name] [varchar](50) NULL,
    [sal] [int] NULL
) 

----table 2: emp and databasename: test1
USE [test]
CREATE TABLE [dbo].[emp]
(
    [id] [int] NULL,
    [name] [varchar](50) NULL,
    [sal] [int] NULL
) 

INSERT [dbo].[emp] ([id], [name], [sal]) 
VALUES (50, N'kl', 80), 39, N'abc', 10)
go

Target table : emptarget and databasename: test1

USE [test1]
CREATE TABLE [dbo].[emptarget]
(
    [id] [int] NULL,
    [name] [varchar](50) NULL,
    [sal] [int] NULL
) 

Finally need to load data like below

Database: test and table : emptarget

id  |name   |sal
19  |hd |40
1   |g  |10
9   |dk |90
80  |dhe    |80

Database: test1 and table : emptarget

id  |name   |sal
50  |kl |80
39  |abc    |10

I tried like below

USE [test]
GO

insert into emptarget 
select * from emp 

USE [test1]
GO
insert into emptarget 
select * from emp 

Here I do not want run two queries separately. I need to run querying using single select and insert statement to load data correspong tables with databases.

Please tell me how to write query to achive this task in SQL Server


Actually I have no idea about why you don't do this.

insert into test.emptarget select * from test.emp; 
insert into test1.emptarget select * from test1.emp;

So I think you just want one query to do this.

create procedure emptoemptarget (@DBName nvarchar(10))
as
begin
    declare @sql nvarchar(1000)

    set @sql = 'insert into ' + @DBName + '.emptarget select * from ' + @DBName + '.emp'

    exec (@sql)
end


select dbo.emptoemptarget(name) from sys.databases where name in ('test','test1')
链接地址: http://www.djcxy.com/p/95696.html

上一篇: UITableView backgroundColor在iPad上始终为灰色

下一篇: 使用存储过程在SQL Server中动态更改数据库