如何将执行的表结果更新到同一个表中?

时间:2016-09-19 08:26:26

标签: sql sql-server tsql

我创建了一个包含列名tbl_DistDistrict的表DistCode,区表中有许多重复值,因此我使用以下语句删除了所有重复值:< / p>

select distinct District from tbl_Dist;

已完成,但我没有得到如何将上述执行查询的结果更新到表tbl_Dist

4 个答案:

答案 0 :(得分:1)

您需要print_r($vpcURL); 而不是Delete

Update

要检查将要删除的记录,请使用此功能。

;with cte as
(
Select row_number() over(partition by District order by (select null)) as rn,* 
From yourtable
)
Delete from cte where Rn > 1

答案 1 :(得分:1)

您可以如下所示:

-- Move temp table
SELECT DISTINCT District INTO TmpTable FROM tbl_Dist
-- Delete all data
DELETE FROM tbl_Dist
-- Insert data from temp table
INSERT INTO tbl_Dist
SELECT * FROM TmpTable

<强>更新

首先,运行此查询。您将拥有一个临时表,其中包含主表(tbl_Dist)

的不同数据
-- Move temp table
SELECT DISTINCT District INTO TmpTable FROM tbl_Dist

然后运行以下查询以删除所有数据

DELETE FROM tbl_Dist

最后,运行以下查询将所有不同的数据插入主表。

-- Insert data from temp table
INSERT INTO tbl_Dist
SELECT * FROM TmpTable

答案 2 :(得分:0)

如果您想保留此查询,可以将其保留在视图中,通过该视图编写更新查询。该表将更新

答案 3 :(得分:0)

试试这个脚本

DELETE FROM tbl_Dist 
WHERE District = District 
AND DistCode > DistCode