Python 使用PyODBC向存储过程传递自定义类型参数
我有一个类型(表)和一个存储过程:Python 使用PyODBC向存储过程传递自定义类型参数,python,tsql,stored-procedures,prepared-statement,pyodbc,Python,Tsql,Stored Procedures,Prepared Statement,Pyodbc,我有一个类型(表)和一个存储过程: CREATE TYPE [Scheduler].[CondType] AS TABLE (condition VARCHAR(32)); CREATE PROCEDURE [Scheduler].[SP_GetResult] (@current_time AS NVARCHAR(5), -- "%HH:%MM" @cond_table [Scheduler].[CondType] READ
CREATE TYPE [Scheduler].[CondType] AS TABLE (condition VARCHAR(32));
CREATE PROCEDURE [Scheduler].[SP_GetResult]
(@current_time AS NVARCHAR(5), -- "%HH:%MM"
@cond_table [Scheduler].[CondType] READONLY)
AS
SELECT [name], [sched_time], [condition]
FROM [Scheduler].[ScheduleTable]
WHERE [condition] IN (SELECT condition FROM @cond_table)
AND @current_time = [sched_time]
我想使用Python中的简单文本参数和复杂(列表/表)参数调用此存储过程:
# not important technical details
tokenstruct = ...
conn_str = "Driver=%s;Server=tcp:%s,1433;Database=%s;" % (cfg.driver, cfg.sql_server, cfg.sql_database)
conn = pyodbc.connect(conn_str, attrs_before = { 1256:tokenstruct })
cursor = conn.cursor()
# input data
hour_and_minute = "08:00"
conditions = ["tuesday", "weekend"]
sql = "{ call Scheduler.SP_GetResult(@current_time=?, @cond_table=?) }"
# execute stored procedure
cursor.execute(sql, (hour_and_minute, conditions)) # but how to pass arguments properly here?
result_set = cursor.fetchall()
当我尝试执行时,简单参数是可以的,但是对于表参数,我得到了如下异常:
pyodbc.ProgrammingError:('42000'、'[42000][Microsoft][ODBC驱动程序17 for SQL Server][SQL Server]列、参数或变量#2:找不到数据类型星期二。(2715)(SQLParamData))
或
pyodbc.ProgrammingError:('42000'、'[42000][Microsoft][SQL Server的ODBC驱动程序17][SQL Server]列、参数或变量#2:找不到数据类型CondType.(2715)(SQLParamData)'))
问题:如何正确传递表类型参数
如果我从SQL控制台执行此操作,它可以正常工作:
DECLARE @DL CondType;
INSERT @DL VALUES ('tuesday'), ('weekday');
EXEC [Scheduler].[SP_GetResult] @current_time = '08:00', @cond_table=@DL;
GO
我试图修改传递的参数,但总是出现类似错误:
conditions = ["tuesday", "weekend"]
conditions = [("tuesday", ), ("weekend", )]
conditions = ("tuesday", "weekend")
conditions = (("tuesday", ), ("weekend", ))
旁注:存储过程不应使用
sp
前缀。微软已经这样做了,而且你确实有可能在将来的某个时候发生名称冲突。最好只是简单地避免使用sp.
并使用其他东西作为前缀,或者根本不使用前缀@马克:好的,谢谢你提供的信息!(我不是数据库专家)可能相关:@elaspog你找到解决方案了吗?我面临着类似的问题。旁注:您不应该在存储过程中使用sp
前缀。微软已经这样做了,而且你确实有可能在将来的某个时候发生名称冲突。最好只是简单地避免使用sp.
并使用其他东西作为前缀,或者根本不使用前缀@马克:好的,谢谢你提供的信息!(我不是数据库专家)可能相关:@elaspog你找到解决方案了吗?我面临着类似的情况。