我正在用SQL查询编写一个powershell代码,以从我们的一个数据库中获取信息,然后将该信息放入变量中以供进一步使用。 我的整个代码都能正常工作,并且确实可以完成我想要的工作。
但是在这段代码中的某些地方会产生两个错误,我无法弄清楚如果脚本实际上在执行应有的操作会发生什么情况。
$Server = "######"
$Database = "######"
$UserSqlQuery = "SELECT [UdstyrsId]
,[Model]
,[Serienr]
,[Udlevdato]
,[Repnr]
,[Notat]
FROM [IT-Support].[dbo].[Udstyrsoplysninger] where aflevdato is null and repnr = $repnr"
function ExecuteSqlQuery($Server, $Database, $UserSQLQuery)
{
$Datatable = New-Object System.Data.DataTable
$Connection = New-Object System.Data.SQLClient.SQLConnection
$Connection.ConnectionString = "server='$Server';database='$Database';integrated security=true;"
$Connection.Open()
$Command = New-Object System.Data.SQLClient.SQLCommand
$Command.Connection = $Connection
$Command.CommandText = $UserSQLQuery
$Reader = $Command.ExecuteReader();
$Datatable.Load($Reader);
$Connection.Close()
return $Datatable
}
$ResultsDataTable = New-Object System.Data.DataTable
$ResultsDataTable = ExecuteSqlQuery $Server $Database $UserSqlQuery
Exception calling "ExecuteReader" with "0" argument(s): "Incorrect syntax near '='."
At C:\Users\adm-#######\Desktop\UserResignation.ps1:70 char:13
+ $Reader = $Command.ExecuteReader();
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : SqlException
Exception calling "Load" with "1" argument(s): "Value cannot be null.
Parameter name: dataReader"
At C:\Users\adm-#######\Desktop\UserResignation.ps1:71 char:13
+ $Datatable.Load($Reader);
+ ~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ArgumentNullException
第70行和第71行是脚本中的以下行:
$Reader = $Command.ExecuteReader();
$Datatable.Load($Reader);
答案 0 :(得分:2)
您忘了为查询的$repnr
条件声明where
,因此您得到语法错误where aflevdato is null and repnr =
。
$repnr = 123
$UserSqlQuery = "SELECT [UdstyrsId]
,[Model]
,[Serienr]
,[Udlevdato]
,[Repnr]
,[Notat]
FROM [IT-Support].[dbo].[Udstyrsoplysninger] where aflevdato is null and repnr = $repnr"