简体   繁体   English

如何将来自 SQL 服务器的 Python 结果保存到 SQL 表中

[英]How to save Python results from SQL server - into SQL table

Please help me to save the results of the Python query through the SQL server - to the SQL table.请帮我把通过SQL服务器的Python查询结果保存到SQL表中。

This script works perfect if the Python script always gives the same number of columns:如果 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'

The problem is, the Python script can produce a different number of columns each time, including columns with new names.问题是,Python 脚本每次可以生成不同数量的列,包括具有新名称的列。

Script:脚本:

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')

Gives an error message:给出错误信息:

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 ')'.

and does not fit to my needs, because I need to add the results to an existing table, and not to recreate each time.并且不符合我的需要,因为我需要将结果添加到现有表中,而不是每次都重新创建。

I tried the following: 1. run the Python script for the 1st time and pull out all the column names, which will then be inserted - into @columns variable 2. if existing table (tmp) doesn't have some columns from the step 1 - update it 3. run the same Python script for the 2nd time, but instead of我尝试了以下操作: 1. 第一次运行 Python 脚本并拉出所有列名,然后将这些列名插入到@columns 变量中 2. 如果现有表 (tmp) 没有步骤中的某些列1 - 更新它 3. 第二次运行相同的 Python 脚本,但不是

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

use:用:

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'

Where @columns is a list of columns obtained in step 1. an error message occurs:其中@columns 是在步骤 1 中获得的列列表。出现错误消息:

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

Then I try to do it through exec ().然后我尝试通过exec()来做。 To avoid quotation marks problems, I create separate variables for each query value.为了避免引号问题,我为每个查询值创建了单独的变量。

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)

an error message occurs:出现错误消息:

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

If I run the same query through select instead of exec, it forms the correct query string:如果我通过 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

This is the third time I create the topic.这是我第三次创建主题。 I'm looking for the solution for many days but seriously stucked.我正在寻找解决方案很多天,但严重卡住了。 If some more information is needed, please let me know.如果需要更多信息,请告诉我。

Thank you so much to everyone, who will share any ideas, thoughts on how to get the results.非常感谢大家,他们将分享任何想法,如何获得结果的想法。 Even if there is no ready-made solution.即使没有现成的解决方案。

The answer is - escape single quotes in the Python construction script.答案是——在 Python 构建脚本中转义单引号。 1) I should have written the script the following way: 1)我应该按以下方式编写脚本:

declare @columns nvarchar(255) = '[col1]
           ,[col2]
           ,[col3]'
declare @for_language nvarchar(255) = 'N''Python'''
declare @for_output_data_1_name nvarchar(255) = 'N''df'''
declare @for_script nvarchar(max) = '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]
})'''

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)

2) temporarily substitute exec by select 3) extract the constructed script from the string 4) run the script from the string separately from the constructor - whether it works. 2) 暂时用 select 替换 exec 3) 从字符串中提取构造的脚本 4) 与构造函数分开运行字符串中的脚本 - 是否有效。 5) if doesn't - to repare the script: primarily on the string level and then in the constructor 5)如果没有 - 重新编写脚本:主要在字符串级别,然后在构造函数中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM