如何在 sequel Server Management Studio 2017 中使用正确的语法直接 运行 python 编码

How to run python code directly with correct syntax within sequel server management studio 2017

我写了一个 python 脚本,它通过 "import pyodbc" 从 sql 获取数据 这个脚本提取的数据被解析到一个短信网关 API 来发送短信相应地给客户。这在 python.

中工作正常

但是,现在我想编写一个 sql 存储过程,每次在我的业务中生成新发票时,它将 运行 发送 phone 号码的数据 +通过同一 sql 存储过程中的此 python python 脚本发送消息。

我现在遇到的问题是用 ssms 2017 编写这个 python 脚本并在没有语法错误的情况下执行它。考虑到我使用的是 sql 2017,我分别启用了 python 和 r。

execute sp_execute_external_script
@language = N'Python',
@script =  N'

import africastalking

username = "sandbox"
apikey = "bf62be6"
africastalking.initialize(username, apikey)
sms = africastalking.SMS
recipients = ["+254797301255"]
message = ["Test from SQL"]
sender = "MegaLtd"

try:
    response = sms.send(message, recipients, sender)
    print(response)
except Exception as e:
    print(f"Houston, we have a problem {e}")

'

这是我收到的错误

Msg 39004, Level 16, State 20, Line 2
A 'Python' script error occurred during execution of 'sp_execute_external_script' with HRESULT 0x80004004.
Msg 39019, Level 16, State 2, Line 2
An external script error occurred: 

Error in execution.  Check the output for more information.
Traceback (most recent call last):
  File "<string>", line 3, in <module>
  File "C:\PROGRA~1\MICROS~3\MSSQL1~1.MPR\MSSQL\EXTENS~1\MPRYCESQLSEVER01D611E8A-CDE1-4F30-9FAC-0BB13871A3DE\sqlindb.py", line 59
    print(f"Houston, we have a problem {e}")
                                          ^
SyntaxError: invalid syntax

SqlSatelliteCall error: Error in execution.  Check the output for more information.
STDOUT message(s) from external script: 
SqlSatelliteCall function failed. Please see the console output for more information.
Traceback (most recent call last):
  File "C:\Program Files\Microsoft SQL Server\MSSQL14.MPRYCESQLSEVER\PYTHON_SERVICES\lib\site-packages\revoscalepy\computecontext\RxInSqlServer.py", line 406, in rx_sql_satellite_call
    rx_native_call("SqlSatelliteCall", params)
  File "C:\Program Files\Microsoft SQL Server\MSSQL14.MPRYCESQLSEVER\PYTHON_SERVICES\lib\site-packages\revoscalepy\RxSerializable.py", line 291, in rx_native_call
    ret = px_call(functionname, params)
RuntimeError: revoscalepy function failed.

您的环境很可能使用 Python 3.5.2

https://docs.microsoft.com/en-us/sql/advanced-analytics/r/use-sqlbindr-exe-to-upgrade-an-instance-of-sql-server?view=sql-server-2017

但是,f-strings 已在 Python 3.6

中引入

所以你要么必须以某种方式升级你的 Python,要么只重写异常处理,例如像这样:

# ORIG: print(f"Houston, we have a problem {e}")
print("Houston, we have a problem {}".format(e))

如果您不确定您的环境使用哪个 Python 版本,您可以查看

import sys
print(sys.version)