我有一个复杂的(*)SQL SELECT
语句,它返回我需要更新的行
如何仅更新SELECT
语句返回的行?
我看到的有关使用SELECT语句更新行的所有帖子都会使用要匹配的字段(How do I UPDATE from a SELECT in SQL Server?)来讨论INNER JOIN对另一个表的讨论
我的陈述是
SELECT * FROM table1 I
INNER JOIN
(SELECT *
FROM (
SELECT INTNO,EFFDTE,
ROW_NUMBER() OVER(PARTITION BY INTNO,EFFDTE ORDER BY EFFDTE DESC) rn
FROM table2 WHERE REFID = 8888 AND EFFDTE IS NOT NULL AND INTNO <> 1234567
) a
WHERE rn = 1) X
ON X.INTNO = I.MEMBNO AND I.ENDDTE = DATEADD(DD,-1,X.EFFDTE)
WHERE I.ENDRSN = 'abc'
答案 0 :(得分:1)
使用此语法
UPDATE a
SET a.col1 = b.col1,
a.col1 = b.col2
.....
.....
FROM update_table a
JOIN(SELECT *
FROM table1 I
INNER JOIN (SELECT INTNO,
EFFDTE,
Row_number()
OVER(
PARTITION BY INTNO, EFFDTE
ORDER BY EFFDTE DESC) rn
FROM table2
WHERE REFID = 8888
AND EFFDTE IS NOT NULL
AND INTNO <> 1234567) X
ON X.INTNO = I.MEMBNO
AND I.ENDDTE = Dateadd(DD, -1, X.EFFDTE)
WHERE I.ENDRSN = 'abc'
AND rn = 1) b
ON a.common_colum = b.common_colum
答案 1 :(得分:0)
试试这个
Update table1
set Col_Name=Value
FROM table1 I
INNER JOIN
(SELECT *
FROM (
SELECT INTNO,EFFDTE,
ROW_NUMBER() OVER(PARTITION BY INTNO,EFFDTE ORDER BY EFFDTE DESC) rn
FROM table2 WHERE REFID = 8888 AND EFFDTE IS NOT NULL AND INTNO <> 1234567
) a
WHERE rn = 1) X
ON X.INTNO = I.MEMBNO AND I.ENDDTE = DATEADD(DD,-1,X.EFFDTE)
WHERE I.ENDRSN = 'abc'
答案 2 :(得分:0)
这是一个方法和理解如何最好地处理SQL查询的问题。
我不需要加入我构建的整个SELECT,我只需要用UPDATE目标替换SELECT,以便针对更新的连接使用逻辑(和公共列)
UPDATE table1
SET field1 = 'MP', field2 = NULL
FROM
table1 I JOIN
(SELECT *
FROM (
SELECT INTNO,EFFDTE,
ROW_NUMBER() OVER(PARTITION BY INTNO,EFFDTE ORDER BY EFFDTE DESC) rn
FROM table2 WHERE REFID = 8888 AND EFFDTE IS NOT NULL AND INTNO <> 1234567
) a
WHERE rn = 1) X
ON X.INTNO = I.MEMBNO AND I.ENDDTE = DATEADD(DD,-1,X.EFFDTE)
WHERE I.ENDRSN = 'abc'