【问题标题】:Incorrect syntax near GO in SQLSQL 中 GO 附近的语法不正确
【发布时间】:2017-09-23 07:32:54
【问题描述】:

我正在连接许多 sql 语句并遇到以下错误。 “GO 附近的语法不正确”和“附近的语法不正确”- 似乎当我删除尾随空格和 go 以及 go 之后的空格,然后 CTRL+Z 放回 GO 这会使错误消失?它很奇怪 为什么?? 如何用 Python 编写代码,谢谢

')
END TRY
BEGIN CATCH
print ERROR_MESSAGE()
END CATCH
GO

【问题讨论】:

  • GO 不是 SQL。将GO 替换为;。来自Microsoft DocsGO is not a Transact-SQL statement; it is a command recognized by the sqlcmd and osql utilities and SQL Server Management Studio Code editor.
  • 它不工作已经试过了。谢谢.. 有时你确实需要 GO,但是是的,分号并不能解决问题。谢谢你
  • 检查 Executing batch T-SQL Scripts containing GO statements 这是 C# 你可以使用逻辑。
  • @bansi 实际上我现在不明白你的参考。但事情就是这样,我实际上是在将多个 sql 文件串联成一个 Main 文件。然后我将去 sql server 执行该文件。我不确定这会有什么帮助,除非我在 sql server 中有一个循环,它将一个接一个地解压缩 Go sql 语句的每一块。你明白我的意思了吗?

标签: python sql-server tsql syntax-error


【解决方案1】:

正如 cmets 中已经提到的,GO 不是 SQL 语法的一部分,而是 Management Studio 中的批处理分隔符。

您可以通过两种方式绕过它,使用Subprocess 调用SqlCmd,或者在Python 中剪切脚本。 Subprocess + SqlCmd 只有在您不关心查询结果的情况下才能真正为您工作,因为您需要解析控制台输出才能获得这些结果。

我需要从过去 SSMS 生成的脚本构建一个数据库,并因此创建了以下函数(更新,因为我现在有一个更好的版本,可以保留 cmets):

def partition_script(sql_script: str) -> list:
    """ Function will take the string provided as parameter and cut it on every line that contains only a "GO" string.
        Contents of the script are also checked for commented GO's, these are removed from the comment if found.
        If a GO was left in a multi-line comment, 
        the cutting step would generate invalid code missing a multi-line comment marker in each part.
    :param sql_script: str
    :return: list
    """
    # Regex for finding GO's that are the only entry in a line
    find_go = re.compile(r'^\s*GO\s*$', re.IGNORECASE | re.MULTILINE)
    # Regex to find multi-line comments
    find_comments = re.compile(r'/\*.*?\*/', flags=re.DOTALL)

    # Get a list of multi-line comments that also contain lines with only GO
    go_check = [comment for comment in find_comments.findall(sql_script) if find_go.search(comment)]
    for comment in go_check:
        # Change the 'GO' entry to '-- GO', making it invisible for the cutting step
        sql_script = sql_script.replace(comment, re.sub(find_go, '-- GO', comment))

    # Removing single line comments, uncomment if needed
    # file_content = re.sub(r'--.*$', '', file_content, flags=re.MULTILINE)

    # Returning everything besides empty strings
    return [part for part in find_go.split(sql_script) if part != '']

使用这个函数,你可以像这样运行包含GO的脚本:

    import pymssql

    conn = pymssql.connect(server, user, password, "tempdb")
    cursor = conn.cursor()
    for part in partition_script(your_script):
        cursor.execute(part)

    conn.close()

我希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-05
    • 1970-01-01
    • 1970-01-01
    • 2017-02-07
    • 2011-08-25
    相关资源
    最近更新 更多