简体   繁体   English

如何将sp_execute_external_script中的值输出到表中

[英]How to output values from sp_execute_external_script into table

Having the following code, how can I output the values from the external python script into a sql table that I can query after. 有了下面的代码,我怎样才能将外部python脚本中的值输出到我可以查询的sql表中。

EXECUTE sp_execute_external_script 
@language = N'Python',
@script = N'
            import pandas as pd
            import numpy as np

            rd = np.random.randn(100)
            df = pd.DataFrame(rd).describe()
            print(df)'

Thanks in advance. 提前致谢。

Indeed, as the R version shows, consider INSERT INTO myTable ... using results from the Python executed script in TSQL, specifying @output_data . 实际上,正如R版本所示,考虑INSERT INTO myTable ...使用TSQL中Python执行脚本的结果,指定@output_data However, first create table to be appended to, aligning columns and types accordingly. 但是,首先创建要附加的表,相应地对齐列和类型。

Additionally, since you use describe() , consider renaming columns prior to output. 此外,由于您使用describe() ,因此请考虑在输出之前重命名列。 Finally, pandas is included by default for the Python Machine Learning Services in SQL Server 2016 as mentioned in this tutorial , so no need to import (possibly same with numpy). 最后, pandas默认包含在SQL Server 2016中的Python机器学习服务中,如本教程中所述 ,因此无需导入(可能与numpy相同)。

DROP TABLE IF EXISTS myTable;

CREATE TABLE myTable (
    [aggregate] varchar(50) NOT NULL,
    [value] float NOT NULL
    )
GO

INSERT INTO myTable    
EXECUTE sp_execute_external_script 
@language = N'Python',
@script = N'import numpy as np

            rd = np.random.randn(100)
            df = pandas.DataFrame(rd).describe().reset_index().rename(columns={"index":"aggregate", 0:"value"})',
@output_data_1_name = N'df';

GO
declare @py nvarchar(max);

set @py = N'from pandas.io.json import json_normalize

rdd = {"documents": [{"id": "1", "score": 0.97},{"id": "2","score": 0.87},{"id": "3", "score": 0.78}],"errors": []}
print(type(rdd))

df = json_normalize(rdd, "documents")
print(df)
print(type(df))
'; 

drop table if exists apiresults
create table apiresults (id int, score float)

insert into apiresults
exec sp_execute_external_script 
    @language = N'Python',
    @script = @py,
    @output_data_1_name =N'df'

select * from apiresults

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

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