我认为我最近使用的脚本可能对某人有用。
要备份表,您可以使用下一个查询:
DECLARE @tableName nvarchar(max), @tableName_bck nvarchar(max)
SET @tableName = 'SomeTable';
SET @tableName_bck = 'SomeTable_bck';
-- Backup
DECLARE @insertCommand nvarchar(max)
--SELECT INTO SomeTable_bck FROM SomeTable
SET @insertCommand = 'SELECT * INTO ' + @tableName_bck + ' FROM ' + @tableName
PRINT @insertCommand
EXEC sp_executesql @insertCommand
对于恢复,由于表通常可以有 IDENTITY 字段,因此您需要 SET IDENTITY_INSERT ON 并且在插入记录时还需要提供列列表。这就是脚本有点复杂的原因:
DECLARE @tableName nvarchar(max), @tableName_bck nvarchar(max)
SET @tableName = 'SomeTable';
SET @tableName_bck = 'SomeTable_bck';
-- Restore
DECLARE @columnList nvarchar(max)
DECLARE @insertCommand nvarchar(max)
SELECT
@columnList = SUBSTRING(
(
SELECT ', ' + column_name AS [text()]
From INFORMATION_SCHEMA.COLUMNS
WHERE table_name = @tableName
ORDER BY table_name
For XML PATH ('')
), 2, 1000);
--INSERT INTO SomeTable(Column1, Column2) SELECT Column1, Column2 FROM SomeTable_bck
SELECT @insertCommand = 'INSERT INTO ' + @tableName + '(' + @columnList + ') SELECT ' + @columnList + ' FROM ' + @tableName_bck
IF EXISTS (
SELECT column_name, table_name
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_schema = 'dbo' AND table_name = @tableName
AND COLUMNPROPERTY(object_id(table_name), column_name, 'IsIdentity') = 1
)
BEGIN
SET @insertCommand =
'SET IDENTITY_INSERT ' + @tableName + ' ON;'
+ 'TRUNCATE TABLE ' + @tableName + ';'
+ @insertCommand + ';'
+ 'SET IDENTITY_INSERT ' + @tableName + ' OFF;'
/*
SET IDENTITY_INSERT SomeTable ON
TRUNCATE TABLE SomeTable
INSERT INTO SomeTable(Column1, Column2) SELECT Column1, Column2 FROM SomeTable_bck
SET IDENTITY_INSERT SomeTable OFF
*/
END
ELSE
BEGIN
SET @insertCommand =
'TRUNCATE TABLE ' + @tableName + ';'
+ @insertCommand
/*
TRUNCATE TABLE SomeTable
INSERT INTO SomeTable(Column1, Column2) SELECT Column1, Column2 FROM SomeTable_bck
*/
END
PRINT @insertCommand
EXEC sp_executesql @insertCommand
很容易看出,您可以根据自己的喜好指定@tableName 和@tableName_bck。例如,这可以在存储过程中,因此脚本是可重用的。