0
我连接了很多sql语句,并且遇到以下错误。 “靠近GO的语法不正确”和“附近的语法错误” - 看来,当我删除尾部空格以及走后的空格和空格,然后按CTRL + Z放回GO时,这会使错误消失?其相当奇怪的 为什么? 我怎么能在Python代码它,谢谢GO附近语法不正确
')
END TRY
BEGIN CATCH
print ERROR_MESSAGE()
END CATCH
GO
我连接了很多sql语句,并且遇到以下错误。 “靠近GO的语法不正确”和“附近的语法错误” - 看来,当我删除尾部空格以及走后的空格和空格,然后按CTRL + Z放回GO时,这会使错误消失?其相当奇怪的 为什么? 我怎么能在Python代码它,谢谢GO附近语法不正确
')
END TRY
BEGIN CATCH
print ERROR_MESSAGE()
END CATCH
GO
正如评论已经提到,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 != '']
使用此功能,您可以运行包含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()
我希望这有助于。
http://stackoverflow.com/a/25681013/5552667 – ZLK
'GO'不是SQL。用';'替换'GO'。来自[Microsoft Docs](https://docs.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-go)'GO不是Transact-SQL语句;它是一个由sqlcmd和osql实用程序和SQL Server Management Studio代码编辑器识别的命令。' – bansi
它已经尝试过了。谢谢..有时你确实需要GO,但是分号并没有这样做.thk – uniXVanXcel