create table company
(
id int identity primary key,
names nvarchar(20)
)
insert into company values('中部印刷网')
insert into company values('睿智软件')
go
create table job
(
id int identity primary key,
jobName nvarchar(20),
companyName nvarchar(20),
)
go
insert into job values('程序员','中部印刷网')
insert into job values('美工','中部印刷网')
insert into job values('软件工程师','睿智软件')
现在又这样的两张表,职位表中没有公司id
现在添加上一个公司id字段 companyId,以前的数据中该列的值都是null 有没有办法
使用一条sql语句 将这个字段的值修改为对应公司表中的id啊?
希望知道的朋友帮忙指点一下 谢谢了!
------解决方案--------------------
- SQL code
create table company(id int identity primary key,names nvarchar(20))insert into company(names) values('中部印刷网')insert into company(names) values('睿智软件')gocreate table job(id int identity primary key,jobName nvarchar(20),companyName nvarchar(20),companyId int)goinsert into job(jobName,companyName,companyId) values('程序员','中部印刷网',null)insert into job(jobName,companyName,companyId) values('美工','中部印刷网',null)insert into job(jobName,companyName,companyId) values('软件工程师','睿智软件',null)go--1update job set companyId = (select id from company where names = t.companyName) from job t--2update job set companyId = m.id from job t , company m where t.companyName = m.namesselect * from job/*id jobName companyName companyId ----------- -------------------- -------------------- ----------- 1 程序员 中部印刷网 12 美工 中部印刷网 13 软件工程师 睿智软件 2(所影响的行数为 3 行)*/drop table company , job
------解决方案--------------------
- SQL code
alter table job add company_id varchar(10) default nullupdate b set b.company_id=a.id from job b,company a where b.companyName=a.names