导入SQL时格式化文本文件

时间:2015-08-18 21:01:46

标签: sql powershell

我似乎无法将txt文件正确导入到sql表中。以下是我的txt文件中的示例:

Split/Skill:;File
;Agent Name;Login ID;Extn;AUX Reason;State;Split/Skill;Time;VDN Name
2;Smith, Joe;13429;64629;;AVAIL;0;93;
2;Gates, Bill;13458;64658;;AVAIL;0;85;

首先我需要忽略第一行,第二行是列名。然后我希望它将换行符视为新行,将分号符号视为新列。 这里尽可能接近:

$location = "path"
    $file = "file"
    $extension = ".txt"
    $full = $location + $file + $extension
    $all = Get-Content $full
    $columns = Get-Content $full
    $columns = $columns.Replace("`n`r",",")
       $table = "CREATE TABLE " + $file + "([" + $columns + "] VARCHAR(255))"
    Write-Host $table

$Connection = New-Object System.Data.SqlClient.SqlConnection
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$Connection.ConnectionString = "Server=server;Database=db;Integrated Security=True"

$SqlCmd.CommandText = $table
$SqlCmd.Connection = $connection

$Connection.Open()
$sqlCmd.ExecuteNonQuery()
$Connection.Close()

基本上将最终输出作为: Table

感谢任何建议!

1 个答案:

答案 0 :(得分:0)

这里有很多假设,包括假设文件是​​可信的。否则,存在巨大 SQL注入漏洞...

$location = "path"
$file = "file"
$extension = ".txt"
$full = $location + $file + $extension
$contents = (cat $full) -split "`r`n" | select -Skip 1

$columns = $contents | select -First 1 | % { $_ -split ";" } | % { if($_-eq ''){' '}else{$_} } | % { "[$_] VARCHAR(255)" }
$columns = $columns -join ","
$create = "CREATE TABLE [$file] ($columns)"

$rows = $contents | select -Skip 1 | % { ($_ -split ";" | % { "'$_'" }) -join "," }
$insert = $rows | % { "INSERT INTO [$file] VALUES($_)" }

$command = (@($create) + $insert) -join [Environment]::NewLine

$Connection = New-Object System.Data.SqlClient.SqlConnection
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$Connection.ConnectionString = "Server=server;Database=db;Integrated Security=True"

$SqlCmd.CommandText = $command
$SqlCmd.Connection = $connection

$Connection.Open()
$sqlCmd.ExecuteNonQuery()
$Connection.Close()

首先将文件(跳过第一行)读入$contents。然后,它从第二行获取列定义,在;上拆分。它用一个空格替换任何空字符串。然后将剩余的行作为insert语句,再次拆分;,并将它们作为单个命令连接到create语句。