-- data
id id_emp emp_make
1 1 小明
2 2 小明
3 2 中明
4 大明
5 无明
-- employee
id emp
1 小明
2 中明
3 大明
首先
data表的emp_make不能为null
id_emp和employee表的id关联
我现在想将data表中id_emp为null和'',并且emp_make在employee表中也能找到对应的记录的时候
就将id_emp更新为employee表中中对应的id
也就是最终data表中的结果将变成
id id_emp emp_make
1 1 小明
2 2 小明
3 2 中明
4 3 大明
5 无明
下面是建表语句
-- ----------------------------
-- Table structure for [dbo].[employee]
-- ----------------------------
DROP TABLE [dbo].[employee]
GO
CREATE TABLE [dbo].[employee] (
[id] int NOT NULL ,
[emp] nvarchar(10) NULL
)
GO
-- ----------------------------
-- Records of employee
-- ----------------------------
INSERT INTO [dbo].[employee] ([id], [emp]) VALUES (N'1', N'小明');
GO
INSERT INTO [dbo].[employee] ([id], [emp]) VALUES (N'2', N'中明');
GO
INSERT INTO [dbo].[employee] ([id], [emp]) VALUES (N'3', N'大明');
GO
-- ----------------------------
-- Indexes structure for table employee
-- ----------------------------
-- ----------------------------
-- Primary Key structure for table [dbo].[employee]
-- ----------------------------
ALTER TABLE [dbo].[employee] ADD PRIMARY KEY ([id])
GO
-- ----------------------------
-- Table structure for [dbo].[data]
-- ----------------------------
DROP TABLE [dbo].[data]
GO
CREATE TABLE [dbo].[data] (
[id] int NOT NULL ,
[id_emp] int NULL ,
[emp_make] nvarchar(10) NULL
)
GO
-- ----------------------------
-- Records of data
-- ----------------------------
INSERT INTO [dbo].[data] ([id], [id_emp], [emp_make]) VALUES (N'1', N'1', N'小明');
GO
INSERT INTO [dbo].[data] ([id], [id_emp], [emp_make]) VALUES (N'2', N'2', N'小明');
GO
INSERT INTO [dbo].[data] ([id], [id_emp], [emp_make]) VALUES (N'3', N'2', N'小明');
GO
INSERT INTO [dbo].[data] ([id], [id_emp], [emp_make]) VALUES (N'4', null, N'大明');
GO
INSERT INTO [dbo].[data] ([id], [id_emp], [emp_make]) VALUES (N'5', null, N'无明');
GO
-- ----------------------------
-- Indexes structure for table data
-- ----------------------------
-- ----------------------------
-- Primary Key structure for table [dbo].[data]
-- ----------------------------
ALTER TABLE [dbo].[data] ADD PRIMARY KEY ([id])
GO
-- ----------------------------
-- Foreign Key structure for table [dbo].[data]
-- ----------------------------
ALTER TABLE [dbo].[data] ADD FOREIGN KEY ([id_emp]) REFERENCES [dbo].[employee] ([id]) ON DELETE NO ACTION ON UPDATE NO ACTION
GO
------解决方案--------------------
UPDATE [data]
SET id_emp=employee.id
FROM [data] LEFT JOIN employee ON [data].emp_make=employee.emp
WHERE ISNULL([data].id_emp,'')=''
------解决方案--------------------
update [data]
set [id_emp]=b.[id]
from [data] a,[employee] b
where (a.id_emp is null or a.id_emp='') and a.emp_make=b.emp
------解决方案--------------------
update [data]
set [id_emp]=b.[id]