SQL loop with python and pyodbc
<p>I want to create a query loop, which do interativ steps from one instance to the next. After fetching the right data i will do some calculation and write the new information back in the date base with specific relations.</p>

<pre><code>Example Set up
Firt loop = [Aggregation Level](1, 2, 3)
Second loop = Product(A, B, C)
Time = (2001,2002,2003)

1. First loop 
Aggregation level "1", Product "A", Fetch all years (2001, 2002, 2003)
Output = [
(2001,'10 pc','20 €')
(2002,'8 pc','18 €')
(2003,'82 pc','5000 €')]

2. Second loop
Aggregation level "1", Product "B", Fetch all years (2001, 2002, 2003)
Output = [
(2001,'15 pc','35 €')
(2002,'20 pc','100 €')
(2003,'25 pc','5000 €')]
</code></pre>

<p>I will use the array (row) and do some calculation. Therefore I will transform the data in a specifc structure after this i will get new figures. </p>

<p>In the end I poste my code and I want to use instead of varible <em>[X, Y]</em> in the select statement the index of the imported excel files as loop parameter or is it better to search inside the data base? 
The information already stored in data base.</p>

<p>The variable <em>[X1, Y1]</em> are my new values, which must be written back in the data base with a specific relations, how should I do that to get the right relationship? Primary key or better ways?</p>

<p>Wishes
123GuteLaune</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import pyodbc as py
import openpyxl as ol

#Connection string to access
cnxn = py.connect("DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};UID=admin;UserCommitSync=Yes#;Threads=3;SafeTransactions=0;PageTimeout=5;MaxScanRows=8;MaxBufferSize=2048;FIL={MS Access};DriverId=25;DefaultDir=C:\xxx\Desktop;DBQ=C:\xxx\Desktop\DatabaseMA_Test.mdb")

#Connection string to excel
wb = ol.load_workbook('C:\xxx\Desktop\Beisspieldatensatz.xlsx')
X = wb.get_sheet_by_name("Hierarchie")
tuple(X['A2':'A72']).value

wb = ol.load_workbook('C:\xxx\Desktop\Beisspieldatensatz.xlsx')
Y = wb.get_sheet_by_name("Mat_GR")
tuple(Y['A2':'A51']).value

#Output of the loaded Excel data
print (X,Y)

#Load Data out of MS Access
cursor.execute(
               """
               SELECT Mat_ID, Monat, Jahr, Umsatzmenge, Umsatz
               FROM [TW-DS]
               Order BY Jahr ASC 'this is at the moment not working'
               WHERE Hier_ID = ? 
               and Mat_ID= ?
               """, [X, Y])

    rows = cursor.fetchall()
    print(rows)

    #Mathematical model unfilled

    #Write data back in MS Access
    cursor.execute(
                   """insert into [TW-DS]
                   (Outlier,
                   [Outlier Value])
                   Values 
                   (X1, 
                   Y2)
                   """)
    cnxn.commit()</code></pre>
</div>
</div>
</p>