--demo setup
drop table if exists employees;
drop table if exists departments;
go
CREATE TABLE Employees (
NAME NVARCHAR(20)
,Salary DECIMAL
,DepartmentID INT
)
GO
CREATE TABLE Departments (
DepartmentID INT
,DepartmentName NVARCHAR(20)
)
GO
INSERT INTO Departments
VALUES (1,'Dep1')
INSERT INTO Departments
VALUES (2,'Dep2')
--solution
--Insert data into Employees table
INSERT INTO Employees
SELECT NAME
,Salary
,DepartmentID
FROM OPENROWSET(BULK 'C:\testdata\emp.txt', FORMATFILE = 'C:\testdata\format_file.xml') emp
JOIN Departments dep ON (emp.DepartmentName = dep.DepartmentName)
--verify
select * from Employees
一个可能的解决方案是使用OPENROWSET
假设一个 csv 文件(emp.txt):
假设一个格式文件(format_file.xml):