2017-04-26 21 views
0

多くのSQL文を連結しており、次のエラーが発生しています。 "GO近くの構文が正しくありません"と "近くに不正な構文"が表示される - 後ろのスペースと移動先と移動先の後にスペースを削除してCtrl + Zを押してGOを戻すと、 ?その非常に奇妙な なぜ?? はどのように私はPythonでそれをコーディングでき、すでにコメントで述べたおかげSQLの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を必要とすることもありますが、セミコロンはtrick.thnkをしません。 – uniXVanXcel

答えて

0

は、GOは、Management Studioのではなく、バッチ区切りSQL構文の一部ではありません。

Subprocessを使用してSqlCmdに電話をかけたり、Python内でスクリプトをカットしたりする方法は2通りあります。 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 != ''] 

この機能を使用します私はこれが役に立てば幸い

import pymssql 

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

    conn.close() 

:、あなたはこのようなGOを含むスクリプトを実行することができます。

関連する問題