2017-04-26 70 views
0

我連接了很多sql語句,並且遇到以下錯誤。 「靠近GO的語法不正確」和「附近的語法錯誤」 - 看來,當我刪除尾部空格以及走後的空格和空格,然後按CTRL + Z放回GO時,這會使錯誤消失?其相當奇怪的 爲什麼? 我怎麼能在Python代碼它,謝謝GO附近語法不正確

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

http://stackoverflow.com/a/25681013/5552667 – ZLK

+0

'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

+0

它已經嘗試過了。謝謝..有時你確實需要GO,但是分號並沒有這樣做.thk – uniXVanXcel

回答

0

正如評論已經提到,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() 

我希望這有助於。