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);