批量复制数据到新库

USE newDB							--新库名, 自己改
GO
DECLARE @sourceDbName NVARCHAR(200),@targetName NVARCHAR(200)
SET @sourceDbName='oldDbName'	--旧库名, 自己改
SET @targetName=DB_NAME()
SET NOCOUNT ON
DECLARE @t TABLE (
	rowNum INT IDENTITY(1,1) PRIMARY KEY,
	tableName NVARCHAR(200),
	columnsInfo NVARCHAR(MAX),
	hasIdentity BIT,
	targetDbName NVARCHAR(200),
	sourceDbName NVARCHAR(200),
	insertSQL AS '---- '+tableName+';'+
	CASE WHEN hasIdentity=1 THEN 'SET IDENTITY_INSERT ['+targetDbName+'].dbo.'+tableName+' ON;' ELSE '' END 
	+
	'INSERT INTO ['+targetDbName+'].dbo.['+tableName+'] (' + columnsInfo+') SELECT ' +  columnsInfo + ' FROM ['+sourceDbName+'].dbo.['+tableName+'];'
	+
	CASE WHEN hasIdentity=1 THEN 'SET IDENTITY_INSERT ['+targetDbName+'].dbo.'+tableName+' OFF;' ELSE '' END
	+';'
)
INSERT INTO @t (tableName,columnsInfo,hasIdentity,targetDbName,sourceDbName)
SELECT
t.name
,STUFF((SELECT ',['+c.name+']'
    FROM sys.[columns] AS c WHERE c.[object_id]=t.[object_id] AND c.system_type_id NOT IN (
SELECT s.system_type_id FROM sys.types AS s	WHERE s.name IN ('timestamp')
)
FOR XML PATH('')
),1,1,'')
,CASE WHEN EXISTS(SELECT 1 FROM sys.[columns] AS c WHERE c.[object_id]=t.[object_id] AND c.is_identity=1) THEN 1 ELSE 0 END
,@targetName
,@sourceDbName
FROM sys.tables AS t

DECLARE @sql NVARCHAR(MAX)
SELECT @sql=ISNULL(@sql,'')+insertSQL FROM @t
SET @sql=REPLACE(@sql,';','
')
PRINT @sql
--EXEC (@sql);

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值