SQL Join Query在PowerShell中不起作用

时间:2017-10-10 17:23:15

标签: sql powershell join oledbconnection

我正在尝试将Python脚本转换为PS脚本。该脚本读取访问数据库文件并运行简单查询以将结果发送到CSV文件。查询在没有Python问题的情况下执行,也可以直接从MS Access执行。

查询:

SELECT
  TABLEA.SITE_CODE,
  TABLEB.REG_TITLE,
  TABLEC.G_ORG_TITLE,
  TABLED.BRD_TITLE,
  TABLEA.SITE_TYPE
FROM ((TABLEA
  LEFT JOIN [TABLEC] ON TABLEA.[G_ORG_ID] = TABLEC.[ID])
  LEFT JOIN TABLEB ON TABLEA.[REGION_ID] = TABLEB.[ID])
  LEFT JOIN TABLED ON TABLEA.[BRAND_ID] = TABLED.[ID]
ORDER BY TABLEA.SITE_CODE

这是我正在使用的代码:

$path = "\Path\to\File.mdb"
$QuerySites = "SELECT TABLEA.SITE_CODE, TABLEB.REG_TITLE, TABLEC.G_ORG_TITLE, TABLED.BRD_TITLE, TABLEA.SITE_TYPE FROM ((TABLEA LEFT JOIN [TABLEC] ON TABLEA.[G_ORG_ID] = TABLEC.[ID]) LEFT JOIN TABLEB ON TABLEA.[REGION_ID] = TABLEB.[ID]) LEFT JOIN TABLED ON TABLEA.[BRAND_ID] = TABLED.[ID] ORDER BY TABLEA.SITE_CODE"

$csv = "C:\path\Outfile.csv"
$connection = New-Object -TypeName System.Data.OleDb.OleDbConnection
$connection.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source= $path"

$delimiter = ','

$command2 = $connection.CreateCommand()
$command2.CommandText = $QuerySites
$adapter2 = New-Object -TypeName System.Data.OleDb.OleDbDataAdapter $command2
$dataset2 = New-Object -TypeName System.Data.DataSet
$adapter2.Fill($dataset2)




$connection.Close()

我收到以下错误:

Exception calling "Fill" with "1" argument(s): "IErrorInfo.GetDescription failed with E_FAIL(0x80004005)."
At line:14 char:1
+ $adapter2.Fill($dataset2)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : OleDbException

正如我所说,查询在Python脚本中运行时没有问题,直接来自Access。

我没有找到引导我找到根本原因的资源。

1 个答案:

答案 0 :(得分:0)

为了关键字安全起见,将所有表和字段名称括在方括号中。

SELECT
    [TABLEA].[SITE_CODE],
    [TABLEB].[REG_TITLE],
    [TABLEC].[G_ORG_TITLE],
    [TABLED].[BRD_TITLE],
    [TABLEA].[SITE_TYPE]
FROM (([TABLEA]
    LEFT JOIN [TABLEC] ON [TABLEA].[G_ORG_ID] = [TABLEC].[ID])
    LEFT JOIN [TABLEB] ON [TABLEA].[REGION_ID] = [TABLEB].[ID])
    LEFT JOIN [TABLED] ON [TABLEA].[BRAND_ID] = [TABLED].[ID]
ORDER BY [TABLEA].[SITE_CODE]