我認爲我最近使用的腳本可以對某人有用。
要備份的表,你可以使用一個查詢:
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_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。例如,這可以在一個存儲過程中,所以腳本是可重用的。
備份無法恢復單個表。版本控制存儲表格的定義而不是其內容。 -1 – Andomar
@Andomar,當然你是對的。我刪除了版本控制部分,並進行了編輯以使我的意思更清晰。我同意你的-1,因爲我沒有回答他的具體問題,但是我把它留在這裏,因爲我認爲這比一般回答他的例子還好。感謝您的反饋意見! – David