首页 > 解决方案 > 如何通过 pandas 库 sqlalchemy 执行 SQL while 循环。不要关闭这个问题,因为我没有找到任何关于这个的答案

问题描述

我正在尝试通过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

当我只尝试更新语句时,它工作正常,但随后为拆分提供了优先级,所以我尝试使用 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)

在此先感谢您的帮助。

标签: pythonpandassplit

解决方案


推荐阅读