[英]T-SQL Update Table From Select Flow
I was wondering how sql is executed when updating from a select statement when there is no where clause.我想知道在没有 where 子句的情况下从 select 语句更新时如何执行 sql 。
Example:例子:
Table 1表格1
+---------+-----------+
| Column1 | Column2 |
+---------+-----------+
| 3097 | Empty |
| 3097 | Empty |
+---------+-----------+
Table 2表 2
+---------+--------------------+
| Column1 | Column2 |
+---------+--------------------+
| 3097 | Camberwell |
| 3097 | Camberwell North |
+---------+--------------------+
Update a
Set a.column2 = b.column2
From Table1 a
Inner join Table2 b On a.Column1=b.Column1
Does it mean that it'll update Column2 from a with Camberwell North for all rows?这是否意味着它将使用 Camberwell North 更新所有行的 Column2 ?
After Editing:--编辑后:--
WITH X AS
(
SELECT * FROM
(
SELECT ROW_NUMBER() over (order by Column1) As myRowNumber1,Column2 AS Column2tbl1 FROM Table1
)a1
INNER JOIN
(
SELECT ROW_NUMBER() over (order by Column1) As myRowNumber2,Column2 AS Column2tbl2 FROM Table2
)b1
ON a1.myRowNumber1=b1.myRowNumber2
)
UPDATE X
set Column2tbl1=Column2tbl2
This can be Possible using ROWNUMBER().......这可以使用 ROWNUMBER().......
Here I Perfroming ROWNUMBER() on Both the Table then Updating the Table1 then在这里,我在两个表上执行 ROWNUMBER() 然后更新 Table1
we can acheive...... like row 1 table 1 matches with row 1 table 2. Update to Camberwell.我们可以实现......就像第 1 行表 1 与第 1 行表 2 匹配。更新到 Camberwell。 Then row 1 table 1 matches row 2 table 2.
然后第 1 行表 1 匹配第 2 行表 2。
To answer your Question and this may be an interesting Answer.回答您的问题,这可能是一个有趣的答案。 I was able to Test this and determined most standard Joins ( Inner, Left, Full Outer ) gave the Answer of the "First" row and ignored the Second row
我能够对此进行测试并确定大多数标准连接( Inner、Left、Full Outer )给出了“第一”行的答案并忽略了第二行
But, a Right join did one of each:但是,一个右连接做了一个:
I just tried this and was surprised that I didn't get an error.我刚试过这个,很惊讶我没有收到错误。 Instead, as you assumed
Table1.Column2
was updated with the results of the first row from Table2
.相反,正如您所假设的那样,
Table1.Column2
已使用Table2
中第一行的结果进行了更新。
CREATE TABLE #test1 (Col1 int, Col2 varchar(10))
CREATE TABLE #test2 (Col1 int, Col2 varchar(10))
INSERT INTO #test1 (col1) Values (3097), (3097)
INSERT INTO #test2 (Col1, Col2) Values (3097, 'C1'), (3097, 'C2')
UPDATE #test1 SET Col2 = #test2.Col2
FROM #test1 INNER JOIN #test2 ON #test1.Col1=#test2.Col1
The results are:结果是:
SELECT * FROM #test1
Col1 Col2
3097 C1
3097 C1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.