2016-11-15 13 views
0

私はPythonから実行する必要がある複雑なSQL Serverクエリを持っています。Pythonからの複雑なSQL Serverクエリ

SQLクエリは次のようになります。

SELECT * 
FROM(
    SELECT DATEADD(HOUR, CONVERT(INT, SUBSTRING(hour_id, 2, 2)), CAST(FECHA as DATETIME)) as 'Time_', value 
    FROM 
     (
     SELECT * FROM [MyTable] 
     ) as sel 
    UNPIVOT(value for hour_id in (H01, H02, H03, H04, H05, H06, H07, H08, H09, H10, H11, H12, H13, H14, H15, H16, H17, H18, H19, H20, H21, H22, H23, H24)) as unpvte 
) as Q1; 

そして、私は、クエリを実行し、パンダに成果をオンにする機能を作成しました:

import pandas as pd 
import numpy as np 
import datetime 
import pypyodbc 

def execute_sql_command(database_name, server_name, user, password, SQLCommand, index_col=0): 
     """ 
     Executed a query in an SQL Server database and returns a Pandas DataFrame 
     :param database_name: Name of the Database 
     :param SQLCommand: SQL command with no comments 
     :param index_col: Index of the column 
     :return: Pandas DataFrame 
     """ 

     connection_string = 'DRIVER={SQL Server};Database=' + database_name \ 
          + ';SERVER=' + server_name \ 
          + ';UID=' + user \ 
          + ';PWD=' + password 

     connection = pypyodbc.connect(connection_string) 
     cursor = connection.cursor() 

     data = list() 
     idx = list() 
     cursor.execute(SQLCommand) 
     hdr = [tuple[0] for tuple in cursor.description] 

     hdr.pop(index_col) 

     results = cursor.fetchone() 
     if results is not None: 
      results = list(results) 

     while results: 
      idx.append(results[index_col]) # add the index 
      results.pop(index_col) # remove the index from the row (we already accounted for it) 
      data.append(results) # 
      results = cursor.fetchone() 
      if results is not None: 
       results = list(results) 

     connection.close() 

     data = np.array(data) 
     df = pd.DataFrame(data=data, columns=hdr, index=idx) 

     return df 

私はこのエラーを取得しています:

pypyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax close to 'L'.")

私のコードはSELECT * FROM Tableのような単純なクエリでは動作しますが、この複雑なクエリでは失敗します。クエリはMicrosoft SQL Server Management Studioで機能します。

答えて

1

まあ、私は問題が何かを考え出しました。

私は.sqlファイルからクエリを読み取りました。したがって、ファイルはUTF-8形式である必要があります。

次に、SQLコマンドを1行で構成します。これは、\n文字を削除します。