gpt4 book ai didi

sql-server - SQL ExecuteReader 抛出 "Incorrect syntax near GO"

转载 作者:行者123 更新时间:2023-12-01 12:23:48 31 4
gpt4 key购买 nike

我使用了一个我发现的 T-SQL 命令 here获取我的数据库表的碎片。当我在 Management Studio 中执行 T-SQL 时,一切正常。如果我在 PowerShell 中使用它,我会收到以下错误(翻译自德语):

Exception when calling "ExecuteReader" with 0 Argument(s): "Incorrect syntax near 'GO'.Incorrect syntax near 'GO'."In Zeile:17 Zeichen:6+      $Result = $cmd.ExecuteReader()+      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException    + FullyQualifiedErrorId : SqlException

This is the part of my script which throws the error

foreach ($table in $tables)
{
$Data = New-Object System.Data.DataTable
$cmd = New-Object System.Data.SqlClient.SqlCommand
$getFragRate = "
-- SQL Command von Microsoft um die Index Fragmentation zu überprüfen
USE Logik;
GO
SELECT a.index_id, name, avg_fragmentation_in_percent
FROM sys.dm_db_index_physical_stats (DB_ID(N'Logik'), OBJECT_ID(N'$($table)'), NULL, NULL, NULL) AS a
JOIN sys.indexes AS b ON a.object_id = b.object_id AND a.index_id = b.index_id;
GO
"
$cmd.CommandText = $getFragRate
$cmd.Connection = $con
$Result = $cmd.ExecuteReader()
$Data.Load($Result)
$Data
}

为什么会出现这个错误?

我用来执行此操作的用户具有 sysadmindb_ddladmindb_owner 权限。

编辑:另一个 T-SQL 命令,可以让我的数据库的所有表在 PowerShell 中正常工作。

最佳答案

GO 不是 T-SQL 命令 - 因此您不能在从 PowerShell 执行的 T-SQL 语句中使用它。

GO 是 SQL Server Management Studio 使用的批处理分隔符。

您需要自己将该语句分解为多个单独的语句,然后一个一个地执行。

关于sql-server - SQL ExecuteReader 抛出 "Incorrect syntax near GO",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41814153/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com