2017-06-19 354 views
0

你好,我正試圖在for循環中創建一個while循環。該代碼將爲我生成一堆SQL Drop索引語句,因此我不必輸入除表名之外的任何內容。 excel文件將包含完成Drop Index語句所需的所有信息。這將節省我幾個小時的打字時間。While循環嵌套for循環

預期輸出: 運行在一個循環,會問我一個新的表名,然後運行該代碼,並問了我和另一個表名或完成工作的代碼。

這實際上與

from openpyxl import load_workbook 
wb = load_workbook(filename='UnusedIndexes.xlsx') 
ws = wb['Indexes1'] 

ws.cell(row=2, column=2) 
ws.cell(row=2, column=2).value 
tablename = input("What Table Do you Want: ") 

for i in range(1,200,1): 
    if ws.cell(row=i, column=1).value == tablename: 
     print("IF EXISTS (SELECT * FROM sys.indexes WHERE NAME = N'[", ws.cell(row = i, column = 2).value, "]')\nDROP INDEX [" + ws.cell(row = i, column = 2).value + "] ON " 
       + "[dbo].[" + tablename + "]\nGO\n") 

在這裏工作是我試圖讓while循環上班工作的代碼。

from openpyxl import load_workbook 
 
wb = load_workbook(filename='UnusedIndexes.xlsx') 
 
ws = wb['Indexes1'] 
 

 
ws.cell(row=2, column=2) 
 
ws.cell(row=2, column=2).value 
 
tablename = input("What Table Do you Want: ") 
 
finished = 'n' 
 

 
while finished == 'n': 
 
    for i in range(1,200,1): 
 
     if ws.cell(row=i, column=1).value == tablename: 
 
      print("IF EXISTS (SELECT * FROM sys.indexes WHERE NAME = N'[", ws.cell(row = i, column = 2).value, "]')\nDROP INDEX [" + ws.cell(row = i, column = 2).value + "] ON " 
 
        + "[dbo].[" + tablename + "]\nGO\n") 
 
     else: 
 
      finished = input("Would you like to enter a new tablename(y/n): ") 
 
     if finished == 'y': 
 
      break

Excel文件格式

  • 的Excel文件名:UnusedIndexes.xlsx
  • SHEETNAME:Indexes1
  • A柱:表名
  • B列:IndexName

您可以使用A和be中的任何文本(字符串)值。只需要在For循環中保留Print語句的功能

回答

0

找出我自己的問題。我有while循環有點愚蠢。如果有人感興趣,這裏是完整的代碼。

from openpyxl import load_workbook 
wb = load_workbook(filename='UnusedIndexes.xlsx') 
ws = wb['Indexes1'] 

ws.cell(row=2, column=2) 
ws.cell(row=2, column=2).value 
finished = 'y' 

while finished != 'n': 
    tablename = input("Enter a tablename for the indexes: ") 
    print("This is the tablename: " + tablename) 
    for i in range(1, 200, 1): 
     if ws.cell(row=i, column=1).value == tablename: 
      print("IF EXISTS (SELECT * FROM sys.indexes WHERE NAME = N'[", ws.cell(row=i, column=2).value, "]')\nDROP INDEX [" 
       + ws.cell(row=i, column=2).value + "] ON " + "[dbo].[" + tablename + "]\nGO\n") 
    finished = input("Would you like to do another table(y/n): ")