使用like运算符更新表

时间:2017-08-24 05:07:49

标签: sql sql-server

我有2张桌子 表1

Diagnosis            GroupID
155.0 - blaaaaaa      GAS

表2

Code  GroupID  
155.0   
155.0
155.0
155.0

我确实尝试从第一个

更新第二个表的GroupID
update Table2 set GroupID= GroupID from table 1 where Diagnosis like '%'+Code+'%'

但它不起作用

3 个答案:

答案 0 :(得分:1)

您更新联接的当前语法略有偏差。请尝试使用此代码:

UPDATE t2
SET GroupID = t1.GroupID
FROM Table2 t2
INNER JOIN Table1 t1
    ON t1.Diagnosis LIKE '%' + t2.Code + '%'

答案 1 :(得分:1)

您可以使用以下代码:

UPDATE 
Tb2 SET Tb2.GroupId = Tb1.GroupId
FROM table1 as Tb1 INNER JOIN table2 as Tb2
ON Tb1.Diagnosis LIKE '%'+Tb2.Code+'%';

答案 2 :(得分:0)

这会有所帮助,http://rextester.com/NILBI39557

CREATE TABLE Table1
(
Diagnosis   VARCHAR(255)
,GROUPID VARCHAR(255)
);

Insert Into Table1 Values('155.0 - blaaaaaa','GAS');

CREATE TABLE Table2
(
Code      VARCHAR(255)
,GROUPID VARCHAR(255)
);

Insert Into Table2 VALUES ('155.0', NULL);
Insert Into Table2 VALUES ('155.0', NULL);
Insert Into Table2 VALUES ('155.0', NULL);
Insert Into Table2 VALUES ('155.0', NULL);

SELECT * FROM Table2;

UPDATE T2 
SET    T2.GroupId = T1.GroupId
FROM   Table1 as T1 INNER JOIN Table2 as T2
ON     T1.Diagnosis LIKE '%'+T2.Code+'%';

SELECT * FROM Table2;