使用SQL Server更新table1和table2值

时间:2017-01-24 05:41:17

标签: c# asp.net sql-server

我想用table2手机号更新table1,table1和table2中的公共列是name,但table1名称与initial混合,table2只有名称。

任何人都可以告诉如何更新table1吗?

我试过这个:

update table1 
set table1.mobile = table2.mobile 
from table1 
join table2 on table1.name = table2.name

表1

Name    Mobile
abc 123
def 456

表2

Name    Mobile
abc  x  null
def  Y  Null

我想更新table2 mobile中的table1 mobile

我试过了 更新table1从table1设置table1.mobile = table2.mobile        在table1.name = table2.name

上连接table2

2 个答案:

答案 0 :(得分:0)

您可以使用子查询执行此操作。

update table1 set table1.mobile = (select TOP 1 table2.mobile from table2 where table2.name = substring(table1.name, 0, charindex(' ', table1.name)))

编辑:

我在列值的第一个单词上做了一个子字符串。 " anil y"现在将是" anil"。

答案 1 :(得分:0)

您可以尝试以下内容:

Create table #table1
(
name varchar(10),
mobile int
)
insert into #table1 values ('Anil', 123)
insert into #table1 values ('abc', 888)
insert into #table1 values (NULL, 321)

Create table #table2
(
name varchar(10),
mobile int
)
insert into #table2 values ('Anil y', NULL)
insert into #table2 values ('z abc', NULL)
insert into #table2 values (NULL, NULL)

Update #table2
Set #table2.mobile = #table1.mobile
from #table2, #table1
Where charindex(#table1.name, #table2.name) > 0

Select * from #table2

<强>输出:

Anil y  123
z abc   888
NULL    NULL