我正在将从文件中逐行读取的字符数据加载到SQL表中。该表是:
CREATE TABLE [dbo].[PSFileOrder](
[PSFOrder_Id] [int] IDENTITY(0,1) NOT NULL,
[PSFile] [varchar](255) NOT NULL,
CONSTRAINT [PK_PSFileOrder] PRIMARY KEY CLUSTERED
(
[PSFOrder_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
我正在使用的PowerShell代码是
#LoadPSFile
$PSFile = "d:\ps\xx.ps1"
cls
$xy = Get-content $PSFile
$xy
foreach($xy in $xy) {invoke-sqlcmd -serverInstance localhost\sqlexpress -query "Insert AA.dbo.PSFileOrder(PSFile) Values ('$xy')"}
如果我正在加载的文件是:
#Filename
#The first line will always be the file name
cls
$filter = "*.*"
$folder = "\\localhost\d$\Master\men and their toys"
$filecount = (Get-ChildItem -literalpath $folder -filter $filter).Countem -literalpath $folder -filter $filter).Countem -literalpath $folder -filter $filter).Countem -literalpath $folder -filter $filter).Count
If ($filecount -lt 1) {$filecount = 0}
"There are {0} files in the {1} directory" -f $filecount, $folder
文件加载没有错误。如果文本中有单引号
"There are {0} files in the {1} d'irectory" -f $filecount, $folder
那么我会收到这个错误
Invoke-Sqlcmd : Incorrect syntax near 'irectory'.
Unclosed quotation mark after the character string ' -f $filecount, $folder')
;'.
At C:\Users\RC\AppData\Local\Temp\2ed13f21-5b46-4df4-a5ee-2488c3dd5ee4.ps1:6 char:35
+ foreach($xy in $xy) {invoke-sqlcmd <<<< -serverInstance localhost\sqlexpress -query "Insert AA.dbo.PSFileOrder(PSFile) Values ('$xy')"}
+ CategoryInfo : InvalidOperation: (:) [Invoke-Sqlcmd], SqlPowerShellSqlExecutionException
+ FullyQualifiedErrorId : SqlError,Microsoft.SqlServer.Management.PowerShell.GetScriptCommand
我确实相信该错误是由于我在$ xy变量周围使用单引号编写“-query”语句而引起的。
我的问题是:
我想保持数据库中文本文件和行的一对一关系。
谢谢
钢筋混凝土
有两个答案使我找到了在加载到SQL之前将单引号加倍的正确路径。修改后的代码是
#LoadPSFile
cls
Get-content "d:\ps\xx.ps1" |
Foreach-Object {$_ -replace "'", "''"} |
ForEach-Object{invoke-sqlcmd -serverInstance localhost\sqlexpress -query "Insert AA.dbo.PSFileOrder(PSFile) Values ('$_')"}
最佳答案
您会得到格式错误的SQL语法。我相信快速解决方案是用$xy
中的两个单引号替换任何单引号:
$escaped = $xy.Replace("'", "''")
invoke-sqlcmd -serverInstance localhost\sqlexpress -query "Insert AA.dbo.PSFileOrder(PSFile) Values ('$escaped')"
# or (the same but without the intermediate variable):
invoke-sqlcmd -serverInstance localhost\sqlexpress -query @"
Insert AA.dbo.PSFileOrder(PSFile) Values ('$($xy.Replace("'", "''"))')
"@
但这也许不是最好的方法。不幸的是,我不熟悉
invoke-sqlcmd
功能。如果它支持参数化查询,我会采用这种方式,并按原样提供$xy
值作为参数值(在这种情况下,无需准备$xy
)。
关于sql-server - 通过Powershell将文本加载到SQL Server中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4443143/