我有一个基于条件更新表的SQL查询。我在visual studio中创建了一个迁移文件,如何添加回滚以确保我更新到文件中的更改可以追溯到它是。
INSERT INTO Table(ID,Name,SiteID,Surname)
SELECT
(SELECT MAX(ID) FROM Table) + ROW_NUMBER()OVER (ORDER BY ID),
Name,
10100,
Surname,
FROM Table
WHERE SiteID = 10000 --so it will copy this data 10000 and make a new entry of 10100
您能否建议如何创建回滚,以便删除所有10100条目并返回原来的样式
我可以说吗?delete
from table
where siteID=10100
效率这么高吗?回滚
答案 0 :(得分:0)
DELETE
语句就是DELETE
语句。回滚某些东西意味着撤消到目前为止在未提交的事务中所做的事情。这可能不是“删除”,可能是撤消UPDATE
,或者返回之前删除的行,甚至是DDL更改。
在您的情况下,如果您想删除之前插入的行,那么DELETE
语句就是您所追求的。但这并没有回滚。以下是ROLLBACK
(和COMMIT
)的示例:
--BEGIN a Transaction
BEGIN TRANSACTION Creation;
--Create a table
CREATE TABLE #Sample (ID int IDENTITY(1,1), String varchar(10));
-- insert a row
INSERT INTO #Sample (String)
VALUES ('Hello');
--Rollback the transactions
ROLLBACK TRANSACTION Creation;
--Now, not only has the row never been inserted, the table was not created!
--This will error
SELECT *
FROM #Sample;
GO
--Now, let's create and COMMIT that table this time:
BEGIN TRANSACTION Creation2;
--Create a table
CREATE TABLE #Sample (ID int IDENTITY(1,1), String varchar(10));
-- insert a row
INSERT INTO #Sample (String)
VALUES ('Hello');
--And commit
COMMIT TRANSACTION Creation2;
GO
--Hazaar! data
SELECT *
FROM #Sample;
GO
--And finally, a little play around with some data
BEGIN TRANSACTION Data1;
INSERT INTO #Sample (String)
VALUES ('These'),('are'),('more'),('values');
--Let's Delete the Hello as well
DELETE
FROM #Sample
WHERE ID = 1;
--Inspect mid transction
SELECT *
FROM #Sample;
--Rollback!
ROLLBACK TRANSACTION Data1;
--Oh, the values have gone!
SELECT *
FROM #Sample;
--Notice, however, the ID still increments:
INSERT INTO #Sample (String)
VALUES ('Goodbye');
--Goodbye is ID 6
SELECT *
FROM #Sample;
GO
DROP TABLE #Sample;
希望有助于解释SQL Server术语中ROLLBACK
的用途。