你的位置:首页 > 数据库

[数据库]MS SQL中使用UPDATE ... INNER JOIN ...

昨天的SQL编程中,有使用到一个方法,就是把一个表某一字段更新至另一个表的字段中去。实现这个方法,Insus.NET有尝试了几个方法,下面一一分享出来,让大家参考参考。下面的数据只是模拟了,形式与Insus.NET实际数据相似。使用临时表,你真实表一样。表一:
代码:

CREATE TABLE #Table1 ([Col1] INT NOT NULL PRIMARY KEY,[Col2] VARCHAR(10) NOT NULL,[Col3] VARCHAR(10) NULL)INSERT INTO #Table1 ([Col1],[Col2],[Col3]) VALUES (1,'GF',NULL),(2,'ER',NULL),(3,'SA',NULL),(4,'JK',NULL),(5,'RE',NULL)GO

View Code


表二:

 

代码:

CREATE TABLE #Table2 ([Col1] INT NOT NULL,[Col2] VARCHAR(100) NOT NULL)INSERT INTO #Table2 ([Col1],[Col2]) VALUES(3,'TR'),(2,'QT'),(1,'JN'),(5,'LP'),(4,'TR')GO

View Code


查询2张表的结果:

数据准备好了,看看要求,是需要把表2的Col2列值填充至表一的Col3上,2张表的对应主键均是Col1。

方法一:
 
代码:

DECLARE @r INT =1, @rs INT = 0SELECT @rs = MAX([Col1]) FROM #Table2WHILE @r <= @rsBEGIN  IF EXISTS(SELECT TOP 1 1 FROM #Table2 WHERE [Col1] = @r)  BEGIN    DECLARE @v VARCHAR(10)    SELECT @v = [Col2] FROM #Table2 WHERE [Col1] = @r    UPDATE #Table1 SET [Col3] = @v WHERE [Col1] = @r  END  SET @r = @r + 1END

View Code


看看执行结果:

 

方法二 ,也许不是真正更新,而是获取结果:


代码:

CREATE TABLE #t ([Col1] INT NOT NULL PRIMARY KEY,[Col2] VARCHAR(10) NOT NULL,[Col3] VARCHAR(10) NULL)INSERT INTO #t ([Col1],[Col2],[Col3]) SELECT t1.[Col1],t1.[Col2],t2.[Col2] FROM #Table1 AS t1INNER JOIN #Table2 AS t2 ON (t1.[Col1] = t2.[Col1])

View Code


得到的结果:


方法三,就是使用UPDATE ... INNER JOIN ...语法来处理,简单:

代码:

UPDATE t1SET t1.[Col3] = t2.[Col2]FROM #Table1 AS t1INNER JOIN #Table2 AS t2 ON (t1.[Col1] = t2.[Col1])

View Code


执行结跟方法一的结果相同: