下面的脚本将为源数据库中的所有表生成语句,以将 1000 条随机记录复制到另一个空数据库。
请注意,“select * insert into ...”语句仅在目标表不存在时才有效。
ORDER BY 使用表的主键。
如果有的话。
SELECT CONCAT('SELECT ',
'TOP 1000 ',
'* INSERT INTO ',
'[TargetDb]', -- replace with the name of the database you want to copy to
'.',QUOTENAME(t.TABLE_NAME),
' FROM ',QUOTENAME(t.TABLE_SCHEMA),'.',QUOTENAME(t.TABLE_NAME),
' ORDER BY ' + QUOTENAME(k.PrimaryKeyName),';'
) as InsertStatement
FROM INFORMATION_SCHEMA.TABLES t
LEFT JOIN (
SELECT TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME as PrimaryKeyName
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE OBJECTPROPERTY(OBJECT_ID(QUOTENAME(CONSTRAINT_SCHEMA) + '.' + QUOTENAME(CONSTRAINT_NAME)), 'IsPrimaryKey') = 1
) k ON (t.TABLE_SCHEMA = k.TABLE_SCHEMA and t.TABLE_NAME = k.TABLE_NAME)
WHERE t.TABLE_TYPE = 'BASE TABLE'
AND t.TABLE_SCHEMA = 'dbo' -- replace with the name of the source database you want to copy from
ORDER BY t.TABLE_SCHEMA, t.TABLE_NAME;