如何从SQL Server保存Python结果-到SQL表中

问题描述 投票:0回答:1

[请帮助我通过SQL服务器将Python查询的结果保存到SQL表。

如果Python脚本始终提供相同数量的列,则此脚本非常完美:

insert INTO [dbo].[tmp]
           ([col1]
           ,[col2])
exec sp_execute_external_script  
       @language =N'Python'    
       ,@script=N'
import pandas as pd
df = pd.DataFrame({
    "name": ["John Smith", "Jane Doe", "Joe Schmo"],
    "address": ["123 Main St.", "456 Maple Ave.", "789 Broadway"]})
'
,@output_data_1_name =  N'df'

问题是,Python脚本每次可以产生不同数量的列,包括具有新名称的列。

脚本:

select * 
into tmp
from
(exec sp_execute_external_script  
       @language =N'Python'    
       ,@script=N'
import pandas as pd
df = pd.DataFrame({
    "name": ["John Smith", "Jane Doe", "Joe Schmo"],
    "address": ["123 Main St.", "456 Maple Ave.", "789 Broadway"],
    "age": [34, 28, 51]
})
'
,@output_data_1_name =  N'df')

给出错误消息:

Msg 156, Level 15, State 1, Line 4
Incorrect syntax near the keyword 'exec'.
Msg 102, Level 15, State 1, Line 14
Incorrect syntax near ')'.

并且不符合我的需要,因为我需要将结果添加到现有表中,而不是每次都重新创建。

我尝试了以下操作:1.第一次运行Python脚本,并拔出所有列名,然后将其插入-@columns变量中2.如果现有表(tmp)在步骤1中没有某些列-更新它3.第二次运行相同的Python脚本,而不是

insert INTO [dbo].[tmp]
           ([col1]
           ,[col2])

用途:

insert INTO [dbo].[tmp]
           (@columns)
exec sp_execute_external_script  
       @language =N'Python'    
       ,@script=N'
import pandas as pd
df = pd.DataFrame({
    "name": ["John Smith", "Jane Doe", "Joe Schmo"],
    "address": ["123 Main St.", "456 Maple Ave.", "789 Broadway"],
    "age": [34, 28, 51]
})
'
,@output_data_1_name =  N'df'

其中@columns是在步骤1中获得的列的列表。出现错误信息:

Msg 207, Level 16, State 1, Line 6
Invalid column name '@columns'.

然后,我尝试通过exec()来实现。为避免引号问题,我为每个查询值创建了单独的变量。]​​>

declare @for_language nvarchar(255) = 'Python'
declare @for_output_data_1_name nvarchar(255) = 'df'
declare @for_script nvarchar(max) = 'import pandas as pd
df = pd.DataFrame({
    "name": ["John Smith", "Jane Doe", "Joe Schmo"],
    "address": ["123 Main St.", "456 Maple Ave.", "789 Broadway"],
    "age": [34, 28, 51]
})'

exec('insert INTO [dbo].[tmp] (' + @columns + ') exec sp_execute_external_script  
       @language =' + @for_language + ',@script=' + @for_script + ',@output_data_1_name ' + @for_output_data_1_name)

出现错误消息:

Msg 102, Level 15, State 1, Line 4
Incorrect syntax near 'pandas'.

如果我通过select而不是exec运行相同的查询,它将形成正确的查询字符串:

insert INTO [dbo].[tmp] ([col1]
           ,[col2]
           ,[col3]) exec sp_execute_external_script   
       @language =Python,@script=import pandas as pd 
df = pd.DataFrame({ 
    "name": ["John Smith", "Jane Doe", "Joe Schmo"], 
    "address": ["123 Main St.", "456 Maple Ave.", "789 Broadway"], 
    "age": [34, 28, 51] 
}),@output_data_1_name df

这是我第三次创建主题。我一直在寻找解决方案很多天,但严重卡住了。如果需要更多信息,请告诉我。

非常感谢每个人,他们将分享有关如何获得结果的任何想法和想法。即使没有现成的解决方案。

[请帮助我通过SQL服务器将Python查询的结果保存到SQL表。如果Python脚本始终提供相同数量的列,则此脚本可以完美地工作:insert INTO [...

python sql sql-server ssms
1个回答
0
投票

答案是-在Python构建脚本中转义单引号。1)我应该按照以下方式编写脚本:

© www.soinside.com 2019 - 2024. All rights reserved.