Ask Learn
Preview
Please sign in to use this experience.
Sign inThis browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
In a previous post, we talked about how to set up Machine Learning Services in SQL Server. Now I will cover the basics of how to Execute R and Python in T-SQL statements. The video below will help you understand the basic syntax, parameter names, and data types used. I also summarized the key steps if you want to read along. Check out the SQL Machine Learning Services documentation to learn more.
Ensure Machine Learning Services is already installed and enabled. After setup I will now show you the basics of executing R and Python code within a T-SQL statement. While I use Python in these samples, you can do everything with R as well.
EXEC sp_execute_external_script @language = N'Python', @script = N'print(3+4)'
Now that we discussed a basic example, let's start adding more pieces.
EXEC sp_execute_external_script @language =N'Python', @script = N'OutputDataSet = InputDataSet;', @input_data_1 =N'SELECT 1 AS Col1';
EXEC sp_execute_external_script @language =N'Python', @script = N'MyOutput = MyInput;', @input_data_1_name = N'MyInput', @input_data_1 =N'SELECT 1 AS foo', @output_data_1_name =N'MyOutput';
EXEC sp_execute_external_script @language =N'Python', @script=N'MyOutput = MyInput;', @input_data_1_name = N'MyInput', @input_data_1 =N'SELECT 1 AS foo,2 AS bar', @output_data_1_name =N'MyOutput' WITH RESULT SETS ((MyColName int, MyColName2 int));
Alright, let's discuss a little more about the input/output data types used between SQL and Python.
EXEC sp_execute_external_script @language =N'Python', @script=N'import pandas as pdc = 1/2d = 1*2s = pd.Series([c,d])df = pd.DataFrame(s)OutputDataSet = df'
EXEC sp_execute_external_script @language =N'Python', @script=N'import pandas as pds = {"col1": [1, 2], "col2": [3, 4]}df = pd.DataFrame(s)OutputDataSet = df'
You now know the basics to execute Python in T-SQL! Did you know you can also write your R and Python code in your favorite IDE like RStudio and Jupyter Notebooks and then remotely send the execution of that code to SQL Server? Check out these documentation links and stay tuned for more blog posts:
https://aka.ms/R-RemoteSQLExecution
https://aka.ms/PythonRemoteSQLExecution
Leave a comment below to ask questions or even tell us about the ways you have used Machine Learning Services in your database.
Please sign in to use this experience.
Sign in