以下T-SQL語句將所有表,主鍵和外鍵從一個數據庫移到另一個數據庫。請注意,SELECT * INTO FROM ... WHERE 1 = 2方法不會創建COMPUTED列和用戶數據類型。同時假設所有的主鍵都聚集
--ROLLBACK
SET XACT_ABORT ON
BEGIN TRAN
DECLARE @dsql nvarchar(max) = N''
SELECT @dsql += ' SELECT * INTO NEWDB.dbo.' + name + ' FROM SRCDB.dbo. ' + name + ' WHERE 1 = 2'
FROM sys.tables
--PRINT @dsql
EXEC sp_executesql @dsql
SET @dsql = N''
;WITH cte AS
(SELECT 1 AS orderForExec, table_name, column_name, constraint_name, ordinal_position,
'PRIMARY KEY' AS defConst, NULL AS refTable, NULL AS refCol
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE OBJECTPROPERTY(OBJECT_ID(constraint_name), 'IsPrimaryKey') = 1
UNION ALL
SELECT 2, t3.table_name, t3.column_name, t1.constraint_name, t3.ordinal_position,
'FOREIGN KEY', t2.table_name, t2.column_name
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS as t1
JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE t2 ON t1 .UNIQUE_CONSTRAINT_NAME = t2.CONSTRAINT_NAME
JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE t3 ON t1.CONSTRAINT_NAME = t3.CONSTRAINT_NAME
AND t3.ordinal_position = t2.ordinal_position
)
SELECT @dsql += ' ALTER TABLE NEWDB.dbo.' + c1.table_name +
' ADD CONSTRAINT ' + c1.constraint_name + ' ' + c1.defConst + ' (' +
STUFF((SELECT ',' + c2.column_name
FROM cte c2
WHERE c2.constraint_name = c1.constraint_name
ORDER BY c2.ordinal_position ASC
FOR XML PATH(''), TYPE
).value('.', 'nvarchar(max)'), 1, 1, '') + ')' +
CASE WHEN defConst = 'FOREIGN KEY' THEN ' REFERENCES ' + c1.refTable + ' (' +
STUFF((SELECT ',' + c2.refCol
FROM cte c2
WHERE c2.constraint_name = c1.constraint_name
ORDER BY c2.ordinal_position ASC
FOR XML PATH(''), TYPE
).value('.', 'nvarchar(max)'), 1, 1, '') + ')' ELSE '' END
FROM (SELECT DISTINCT orderForExec, table_name, defConst, constraint_name, refTable FROM cte) AS c1
ORDER BY orderForExec
--PRINT @dsql
EXEC sp_executesql @dsql
COMMIT TRAN
我不要以爲'哪裏1 = 2'會對你有什麼好處。 –
它會複製表沒有數據 – ShaQue
@Upendra:我不想移動表的記錄,所以我作出的條件爲假 – ShaQue