如何将 Update 语句添加到我即将插入到 table with MS SQL 查询中的选定行?
How do I add Update statement to selected rows I am about to insert into a table with MS SQL query?
我已经绞尽脑汁一段时间了,但没有任何结果。
老实说,我认为我需要重新审视这个问题。
我编写了一个查询,从一个 table 中删除数据并将其放入另一个 table。我无法真正弄清楚的是如何在同一个查询中为我正在移动的那些行更新一列。
下面是查询的样子:
INSERT table1_archive
SELECT * FROM (
DELETE table
OUTPUT
DELETED.*
WHERE <condition1>
) AS RowsToMove;
我要的是还要加
UPDATE table1 SET <my_column> = "" WHERE <condition1>
因为删除和更新的条件相同并且 table,我认为调用两个不同的查询来对完全相同的行执行一些操作是没有意义的。
我想要的是在将行移动到 table1_archive 之前或之后清除 中的数据。
我想我的问题是:如何将此更新语句应用到我即将插入到 table1_archive 中的选定行?
回答
这个问题变得有点多余,因为 UPDATE 语句不是实现我想要的所必需的。我可以在 SELECT 语句中列出我的所有列,并将 替换为 NULL 或 '''.
您可以在一条语句中执行此操作 - 但它需要您枚举列。
假设您的表有列 (col1, col2, col3, mycol)
,其中 mycol
在复制到存档时应设置为 null
,您可以这样写:
with del as (
delete ...
output deleted.*
where ...
)
insert into table1_archive (col1, col2, col3, mycol)
select col1, col2, col3, null
from del
UPDATE table1 SET
table1.my_column1= table2.my_column1
FROM
example_table1 AS table1
INNER JOIN example_table2 AS table2
ON table1.ID = table2.ID
WHERE
table1.my_column2 = <condition1>
你也可以尝试这个解决方案
UPDATE example_table1 table1 ,
(SELECT
my_column1, my_column2
FROM example_table2
WHERE
table1.my_column3=<condition1>
) table2
SET
table1.my_column1 = table2.my_column1,
table1.my_column2 = table2.my_column2
where table1.ID = table2.ID
您可以简单地在 select 语句中操作要更新的列。
INSERT INTO table1_archive
SELECT Col1,Col2...,"" AS <my_column> FROM (
DELETE table
OUTPUT
DELETED.*
WHERE <condition1>
) AS RowsToMove;
我已经绞尽脑汁一段时间了,但没有任何结果。 老实说,我认为我需要重新审视这个问题。 我编写了一个查询,从一个 table 中删除数据并将其放入另一个 table。我无法真正弄清楚的是如何在同一个查询中为我正在移动的那些行更新一列。 下面是查询的样子:
INSERT table1_archive
SELECT * FROM (
DELETE table
OUTPUT
DELETED.*
WHERE <condition1>
) AS RowsToMove;
我要的是还要加
UPDATE table1 SET <my_column> = "" WHERE <condition1>
因为删除和更新的条件相同并且 table,我认为调用两个不同的查询来对完全相同的行执行一些操作是没有意义的。
我想要的是在将行移动到 table1_archive 之前或之后清除
我想我的问题是:如何将此更新语句应用到我即将插入到 table1_archive 中的选定行?
回答
这个问题变得有点多余,因为 UPDATE 语句不是实现我想要的所必需的。我可以在 SELECT 语句中列出我的所有列,并将
您可以在一条语句中执行此操作 - 但它需要您枚举列。
假设您的表有列 (col1, col2, col3, mycol)
,其中 mycol
在复制到存档时应设置为 null
,您可以这样写:
with del as (
delete ...
output deleted.*
where ...
)
insert into table1_archive (col1, col2, col3, mycol)
select col1, col2, col3, null
from del
UPDATE table1 SET
table1.my_column1= table2.my_column1
FROM
example_table1 AS table1
INNER JOIN example_table2 AS table2
ON table1.ID = table2.ID
WHERE
table1.my_column2 = <condition1>
你也可以尝试这个解决方案
UPDATE example_table1 table1 ,
(SELECT
my_column1, my_column2
FROM example_table2
WHERE
table1.my_column3=<condition1>
) table2
SET
table1.my_column1 = table2.my_column1,
table1.my_column2 = table2.my_column2
where table1.ID = table2.ID
您可以简单地在 select 语句中操作要更新的列。
INSERT INTO table1_archive
SELECT Col1,Col2...,"" AS <my_column> FROM (
DELETE table
OUTPUT
DELETED.*
WHERE <condition1>
) AS RowsToMove;