SQL 中 GO 附近的语法不正确

uni*_*cel 4 python t-sql sql-server syntax-error

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

')
END TRY
BEGIN CATCH
print ERROR_MESSAGE()
END CATCH
GO
Run Code Online (Sandbox Code Playgroud)

Sla*_*zor 5

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

您可以通过两种方式绕过它,使用Subprocess调用SqlCmd或在 Python 中剪切脚本。该Subprocess+SqlCmd将只有真正为你工作,如果你不关心的查询结果,你会需要分析控制台输出得到这些。

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

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 != '']
Run Code Online (Sandbox Code Playgroud)

使用此功能,您可以运行包含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()
Run Code Online (Sandbox Code Playgroud)

我希望这有帮助。