你能不能:
1)获取表格列表
2) 对于这些表中的每一个,从一个数据库插入到另一个
仅供参考 - 如果您需要比较数据库,Visual Studio 可以进行架构/数据比较,而且它是免费的
这是一个示例脚本。它假设表结构是相同的。您可以使用 print 生成脚本或执行命令(这已被注释掉)
SET NOCOUNT ON
DECLARE
@objectName nvarchar(256)
,@sql nvarchar(max)
,@db1 nvarchar(100) = 'DB_1'
,@db2 nvarchar(100) = 'DB_2'
DROP TABLE IF EXISTS #EmptyTables
;WITH c_EmptyTables AS (
SELECT t.object_id
,s.Name AS SchemaName
,t.Name AS TableName
,p.rows AS RowCounts
,FullName = CONCAT (
QUOTENAME(s.name)
,'.'
,QUOTENAME(t.name)
)
,CAST(ROUND((SUM(a.used_pages) / 128.00), 2) AS NUMERIC(36, 2)) AS Used_MB
,CAST(ROUND((SUM(a.total_pages) - SUM(a.used_pages)) / 128.00, 2) AS NUMERIC(36, 2)) AS Unused_MB
,CAST(ROUND((SUM(a.total_pages) / 128.00), 2) AS NUMERIC(36, 2)) AS Total_MB
FROM sys.tables t
INNER JOIN sys.indexes i ON t.OBJECT_ID = i.object_id
INNER JOIN sys.partitions p ON i.object_id = p.OBJECT_ID
AND i.index_id = p.index_id
INNER JOIN sys.allocation_units a ON p.partition_id = a.container_id
INNER JOIN sys.schemas s ON t.schema_id = s.schema_id
WHERE ISNULL(p.rows, 0) = 0
GROUP BY t.Name
,s.Name
,p.Rows
,t.object_id
)
SELECT *
INTO #EmptyTables
FROM c_EmptyTables
DECLARE cur CURSOR LOCAL FAST_FORWARD
FOR
SELECT FullName
FROM #EmptyTables t
OPEN cur
FETCH NEXT
FROM cur
INTO
@objectName
WHILE @@FETCH_STATUS = 0
BEGIN
SET @sql = 'INSERT INTO ' + @db1 + '.' + @objectName + CHAR(10)
+ 'SELECT * FROM ' + @db2 + '.' + @objectName
+ CHAR(10) + 'GO' + CHAR(10)
PRINT(@sql)
BEGIN TRY
BEGIN TRANSACTION
--EXEC(@sql)
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
IF (@@TRANCOUNT > 0)
ROLLBACK TRANSACTION;
PRINT CHAR(10) + '*** UPDATE FAILED FOR ***';
PRINT CHAR(10) + @sql
PRINT CHAR(10)
SELECT
ERROR_NUMBER() AS ErrorNumber
,ERROR_SEVERITY() AS ErrorSeverity
,ERROR_STATE() AS ErrorState
,ERROR_PROCEDURE() AS ErrorProcedure
,ERROR_LINE() AS ErrorLine
,ERROR_MESSAGE() AS ErrorMessage;
END CATCH
FETCH NEXT
FROM cur
INTO
@objectName
END
CLOSE cur
DEALLOCATE cur