2016-10-20 29 views
1

我想在SQL表上运行脚本,该表将搜索用户主管的表,然后用全名替换主管值。我怎样才能做到这一点?我正在使用MSSQL,并有一个包含此数据的表。搜索SQL表的值,查找该记录中的另一个值并替换为值

Before: 

fullname,username,supervisor 
Timothy Dalton,tdalton,rmoore 
Pierce Brosnan,pbrosnan,rmoore 
Sean Connery,sconnery,rmoore 
Roger Moore,rmoore,dcraig 
Daniel Craig,dcraig, 

After script: 

fullname,username,supervisor 
Timothy Dalton,tdalton,Roger Moore 
Pierce Brosnan,pbrosnan,Roger Moore 
Sean Connery,sconnery,Roger Moore 
Roger Moore,rmoore,Daniel Craig 
Daniel Craig,dcraig, 

感谢

+0

有关问题截图.. HTTP://元。 stackoverflow.com/questions/285551/why-may-i-not-upload-images-of-code-on-so-when-asking-a-question/285557#285557 – Insac

回答

3

尝试是这样的

Update t1 
    set t1.supervisor = t2.Fullname 
from YourTable t1 
    join YourTable t2 on t1.supervisor = t2.username 

此代码没有经过测试...用它

+0

嗨,对不起,问什么t1和t2代表?这些变量是?正如你所看到的,我并不经常使用SQL。 – JamesTheBiker

+0

@JamesTheBiker这些是临时给表格的名字。在SQL中,它被称为别名 –

+0

完美工作。谢谢。 – JamesTheBiker

0

尝试用以下之前,所以一定要备份表查询。 请注意,如果有multiple supervisors with same last name and first name starts with same character,下面的查询将失败。 (例如,如果supervisorrmoorefull nameRoger MooreRoyal Moore,然后下面的查询将更新所有这些名称的导师)

UPDATE y 
SET y.supervisor=y1.fullname 
FROM YourTable y 
JOIN YourTable y1 
     ON y1.fullname like LEFT(y.supervisor,1)+'%' 
      AND LTRIM(RTRIM(SUBSTRING(y1.fullname,CHARINDEX(' ',y1.fullname),LEN(y1.fullname))))=LTRIM(RTRIM(SUBSTRING(y.supervisor,2,LEN(y.supervisor)))) 
相关问题