如果另一列具有相同的值,则将列中每行的数据插入表中

时间:2017-12-21 09:58:15

标签: sql sql-server

我需要转移17,000' ISSI'表1中的值 - >表2使用ID的比较'。不确定是否需要循环,因为ID无序。

表1: - sysdba.C_AccountTable

AccountProductID |    ISSI  | 
-----------------------------
 1QWEqwe         |    113   |
 2qweqwrdsd      |    436   |
 1Eqwe           |    113   |

表2: - dbo.AssetTable

CustomerProductID | ISSI |
--------------------------
    1QWEqwe       |      |
    1Eqwe         |      |
2qweqwrdsd        |      |

预期结果 - dbo.AssetTable

CustomerProductID | ISSI |
--------------------------
    1QWEqwe       | 113  |
    1Eqwe         | 113  |
2qweqwrdsd        | 436  |

(17,000行待改变)

2 个答案:

答案 0 :(得分:0)

这可能是预期的结果

DECLARE @C_AccountTable TABLE (AccountProductID VARCHAR(100),ISSI    INT)
INSERT INTO @C_AccountTable
 SELECT '1QWEqwe'         ,    113   UNION ALL
 SELECT '2qweqwrdsd'      ,    436   UNION ALL
 SELECT '1Eqwe'           ,    113   

DECLARE @AssetTable TABLE(CustomerProductID VARCHAR(100) , ISSI INT)
INSERT INTO @AssetTable
 SELECT   '1QWEqwe',NULL       UNION All     
 SELECT   '1Eqwe'  ,NULL      

 SELECT * FROM @AssetTable
 UPDATE A
 SET A.ISSI=C.ISSI
 FROM @AssetTable A
    INNER JOIN @C_AccountTable C
        ON c.AccountProductID=A.CustomerProductID


 SELECT * FROM @AssetTable

更新前的结果

CustomerProductID   ISSI
 -------------------------
    1QWEqwe         NULL
    1Eqwe           NULL

更新后的结果

CustomerProductID   ISSI
-------------------------
1QWEqwe             113
1Eqwe               113

答案 1 :(得分:0)

UPDATE  T2
SET T2.ISSI = T1.ISSI  
FROM dbo.AssetTable as T2 INNER JOIN sysdba.C_AccountTable as T1
ON T1.AccountProductID  = T2.CustomerProductID;

我已经检查了这个实验

-- Table Creating start

declare @t table(Code varchar(20), name varchar(50))
declare @t1 table(Code varchar(20), name varchar(50))

DECLARE @counter INT = 1;
INSERT INTO @t ([Code],[Name]) VALUES( @counter , 'val 1');
set @counter = @counter + 1
INSERT INTO @t ([Code],[Name]) VALUES( @counter , 'val 2');
set @counter = @counter + 1
INSERT INTO @t ([Code],[Name]) VALUES( @counter , 'val 3');
set @counter =  1
INSERT INTO @t1 ([Code],[Name]) VALUES( @counter , '');
set @counter = @counter + 1
INSERT INTO @t1 ([Code],[Name]) VALUES( @counter , '');
set @counter = @counter + 1
INSERT INTO @t1 ([Code],[Name]) VALUES( @counter , '');


select * from @t
select * from @t1

-- Table Creating End

UPDATE  T2
SET    T2. Name = T1 .Name
FROM   @t1 as T2 INNER JOIN @t as T1
ON     T1. Code = T2 .Code;

select * from @t1