如何通过熊猫库sqlalchemy循环执行SQL

时间:2020-01-20 10:08:17

标签: python pandas split sqlalchemy

我正在尝试通过python执行SQL查询。这是基于我的第一个问题,即如何基于两个数据框(公司扩展名和公司名称的拆分)拆分列。由于我发现很难用python编写代码,因此我使用sql查询来拆分并通过python执行。我能够执行更新之类的查询,但是当我尝试使用循环时却没有输出也没有任何错误。

我的输入:

Original_Input                                            Cleansed_Input                        
DORO INC ( O/S DORO SAFETY & SECURITY)                    DORO INC OS DORO SAFETY SECURITY      
Iris Diagnostics, a Division of Iris International Inc    Iris Diagnostics a Division of Iris 
                                                          International Inc     
GINGI-PAK a division of The Belport Co., Inc.             GINGIPAK a division of The Belport Co Inc 

我的预期输出:

Original_Input                                            Cleansed_Input                             
DORO INC ( O/S DORO SAFETY & SECURITY)                    DORO INC OS DORO SAFETY SECURITY      
Iris Diagnostics, a Division of Iris International Inc    Iris Diagnostics a Division of Iris 
                                                          International Inc     
GINGI-PAK a division of The Belport Co., Inc.             GINGIPAK a division of The Belport Co Inc 
Core_Input                                                Type_Input

Iris Diagnostics a Division of Iris International         Incorporated       
GINGIPAK a division of The Belport                        Company Incorporated

当我只尝试update语句时,它工作正常,但是有一个优先级来进行拆分,因此我尝试使用while循环并通过python执行了无效的操作。它在sql中工作正常,但不能通过python运行。

在代码Tempcompanyname中是我的带有输入和输出的表。 Company_Extension是另一个具有扩展名,缩写和优先级的表。

我的第二张桌子如下。

Name_Extension  Company_Type         Priority
co llc          Company LLC            2
Pvt ltd         Private Limited        8
Corp            orporation             4
Co inc          Company Incorporated   9

这是我的代码。

engine.execute('''Declare @priority int = (select max(priority) from [company_Extension])
              Declare @p int=1
              while @p <= @priority
              begin

              update A 
              set A.Type_input = B.Company_Type 
              from [TempCompanyName]A (nolock), [company_Extension]B  where  A.Cleansed_Input like 
              '%'+B.Name_Extension and Priority=@p

              update A 
              set A.Core_Input =replace(A.[Cleansed_Input],B.Name_Extension,'')
              from [TempCompanyName]A (nolock), [company_Extension]B  where  A.Cleansed_Input like 
              '%'+B.Name_Extension and Priority=@p

              set @p=@p+1
              end''')

engine.execution_options(autocommit=True)

预先感谢您的帮助。

0 个答案:

没有答案