我有一张叫员工的表。
Employee
------------
ID
Name
Age
要向Employee表插入数据,我有一个具有相同表结构的Temp Table,例如#TempEmployee
#TempEmployee
------------
ID
Name
Age
DOB
如果员工表中已经有数据,我想从表中删除数据。我尝试使用以下脚本,但没有用。
DELETE a
FROM #TempEmployee AS a
INNER JOIN Employee b
ON b.Id = a.Id AND b.Name = a.Name
请帮助纠正此问题。
预先感谢
答案 0 :(得分:1)
另一种语法:
DELETE #TempEmployee
FROM #TempEmployee AS a
INNER JOIN Employee b
ON b.Id = a.Id AND b.Name = a.Name
让我展示一个例子:
首先,我们创建持久性表Employee
并填充该表:
CREATE TABLE Employee
(
Id INT,
Name VARCHAR(50),
Age INT
)
INSERT INTO dbo.Employee
(
Id,
Name,
Age
)
VALUES
(1, 'Person_1', 1)
, (4, 'Person_4', 4)
, (5, 'Person_5', 5)
然后我们创建临时表并用数据填充它:
CREATE TABLE #TempEmployee
(
Id INT,
Name VARCHAR(50),
Age INT
)
INSERT INTO #TempEmployee
(
Id,
Name,
Age
)
VALUES
(1, 'Person_1', 1)
, (2, 'Person_2', 2)
, (3, 'Person_3', 3)
下一步是从临时表中删除数据:
DELETE #TempEmployee
FROM #TempEmployee AS a
INNER JOIN Employee b
ON b.Id = a.Id AND b.Name = a.Name
输出将为SELECT * FROM #TempEmployee
:
Id Name Age
2 Person_2 2
3 Person_3 3
答案 1 :(得分:0)
您可以在下面尝试-
DELETE a
FROM #TempEmployee AS a
INNER JOIN Employee b
ON b.Id = a.Id AND b.Name = a.Name
答案 2 :(得分:0)
您需要记住,每个活动用户都有一个临时表,除非您使用双#号。 这意味着,如果两个用户处于活动状态并创建临时表,则他们将创建#TempEmployee的单独副本。如果启动脚本以删除已插入的脚本,则不会影响另一用户。 此外,我建议您使用另一个名称来调用删除过程(假设ID是主键):
DELETE a
FROM #TempEmployee
WHERE id IN (
SELECT ID
FROM Employee)