Uncategorized
56

SQL Machine Learning: SP_execute_external_script

LAB 02 – SQL Server Machine Learning: sp_execute_external_script

La integración de los servicios de Machine Learning con SQL Server se hacen por medio del store procedure sp_execute_external_script el cual permite la ejecución de código R o Python.

Este SP tiene 3 tipos de salidas.

  • Resultset
  • Model
  • Plot

Ejemplo 1: Hola Mundo

Este primer ejemplo ejecuta un codigo con la instruccion print.

Para poder ejecutar el código usaremos el SQL Server management studio conectándonos a la instancia de SQL Server.



EXEC sp_execute_external_script
  @language = N'R',
  @script = N'print(''Hola Mundo'')'
GO
EXEC sp_execute_external_script
  @language = N'Python',
  @script = N'print(''Hola Mundo'')'
GO


Ejemplo 2: Usar imput_data_1 con una consulta TSQL

En este ejemplo vamos a usar los parámetros de entrada que nos ofrece el store procedure para poderle pasar una consulta TSQL.

-- usando R
EXECUTE sp_execute_external_script   
        @language = N'R', 
        @script = N' OutputDataSet <- InputDataSet;',    
        @input_data_1 = N' SELECT name FROM sys.databases order by 1;',
        @input_data_1_name = N''  
WITH RESULT SETS (([NombreBase] nvarchar(max) NOT NULL)); 

EXECUTE sp_execute_external_script   
        @language = N'R', 
        @script = N' OutputDataSet <- Datos;',    
        @input_data_1 = N' SELECT name FROM sys.databases order by 1;',
        @input_data_1_name = N'Datos'  
WITH RESULT SETS (([NombreBase] nvarchar(max) NOT NULL));
--- con python
EXECUTE sp_execute_external_script  
     @language =N'Python',
     @script=N'OutputDataSet=InputDataSet',
     @input_data_1 = N'SELECT name FROM sys.databases order by 1;'
WITH RESULT SETS (([NombreBase] nvarchar(max) NOT NULL))

EXECUTE sp_execute_external_script  
     @language =N'Python',
     @script=N'OutputDataSet=Datos',
     @input_data_1 = N'SELECT name FROM sys.databases order by 1;',
     @input_data_1_name = N'Datos'  
WITH RESULT SETS (([NombreBase] nvarchar(max) NOT NULL))

Ejemplo 3: Usar el dataset Iris de R

Este ejemplo muestra un código R el cual se usara el famoso dataset Iris y su resultado se retorna como dataset de SQL Server

EXECUTE sp_execute_external_script
   @language = N'R',
   @script = N'OutputDataSet <- head(iris)',
   @input_data_1 = N''
WITH RESULT SETS (([Sepal.Length] float, [Sepal.Width] float,
                   [Petal.Length] float, [Petal.Width] float,
                   [Species] varchar(25)));