我遇到PowerShell脚本问题我之前没有做过PowerShell脚本编写。
正如您可以看到我的问题如何将sql表列名称与csv标头进行比较并仅从匹配列的csv插入数据
这是因为我的csv文件带有相同或不同的列,而sql表列是静态的。
我用psedocode给我的尝试
由于缺乏知识,我无法在powershell中执行此操作
$csvfile='E:\ReadCSV\abc.csv'
$sqlTable='MEStable'
$DataSource='DESK20-RN\SQLEXPRESS'
$DataBase='MES'
$ConnectionString ='Data Source={0}; Database={1}; Trusted_Connection=True;' -f $DataSource,$DataBase
$headers = @()
$sqlcol = @()
$data = @{}
if($ConnectionString){
# Get table column name in array
$QueryResult = Invoke-Sqlcmd -ServerInstance $DataSource -Database $DataBase -Query "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME=$sqlTable;"
$NewResults = $QueryResult | Select-object -ExpandProperty COLUMN_NAME
# Need logic here to import csv and add into hash table
# like headers are keys and respective header value in values
# then compare headers with above $sqlcol array and push matched header data into separate header array
# then SQL bulk insert method insert all matched csv data into matched SQL table column name.
}
else{
Write-Host "Error connecting to database"
}
Sql表查询
Create Database MES;
use MES;
drop table if exists MEStable;
Create table MEStable
(
AutoId int not null identity(1,1) primary key,
Employee_id varchar(20) not null,
First_Name varchar(20) not null,
Last_Name varchar(20) not null,
Shift varchar(20) not null,
Day int null,
Night int null
);
示例csv文件
id,fname,lname,shift,day,night
1,ert,sdf,08/21/2017 Day,2,-
2,wer,asdf,08/21/2017 Day,-,1
3,rty,adsf,08/21/2017 Day,1,-
4,yui,adsf,08/21/2017 Day,-,-
5,qwe,asdf,08/21/2017 Day,-,-
6,ret,asdf,08/21/2017 Day,-,-
7,chh,asdf,08/21/2017 Day,-,-
8,sdf,cxvv,08/21/2017 Day,1,-