【问题标题】:Using pymssql, how to call stored procedure with output使用 pymssql,如何使用输出调用存储过程
【发布时间】:2023-03-25 20:05:01
【问题描述】:
  1. 此代码有效,但不确定如何获取输出?

    storedProcedure = "dbo.myproc"
    cursor = conn.cursor()
    query = """DECLARE @test_suite_dispatch_id int;
               exec {sp} @test_suite_id={id},
               @test_suite_dispatch_id = @test_suite_dispatch_id OUTPUT
            """.format( sp=storedProcedure, id=TestSuiteData['TestSuite_ID'])
    print( query )
    cursor.execute( query )
    cursor.close()
    
  2. 如何使用 pymssql 的 callproc 方法使上述内容正常工作?

    此代码不起作用:

    out = None
    cursor.callproc(storedProcedure, 
                    (TestSuiteData['TestSuite_ID'], out))
    

    这也不起作用:

    cursor.callproc(storedProcedure, 
                    [(TestSuiteData['TestSuite_ID']), out])
    

    我也试过了:

    cursor.callproc(storedProcedure, 
                    [(TestSuiteData['TestSuite_ID']), pymssql.output(int)])
    

    cursor.callproc(storedProcedure, 
                    [(TestSuiteData['TestSuite_ID']), pymssql.output(long)])
    

你们觉得呢?

来源:https://stackoverflow.com/a/192032/2965993

【问题讨论】:

标签: python sql-server exec pymssql


【解决方案1】:

好吧,我想通了。

根据您的输出结果,这就是我所做的并且有效:

msg = cursor.callproc(store_proc, (file_name, '0x0a', pymssql.output(str)))
print(msg[2])

显然我的存储过程接受不同的值,但您可以使用它运行。

【讨论】:

    【解决方案2】:

    首先,你要导入pymssql.output

    from pymssql import output
    

    然后,创建一个新变量,它将作为输出参数传递给实际的存储过程(此时您必须知道输出参数将具有哪种类型,如果您不知道,请检查存储过程代码):

    counter = output(int)
    

    您现在要做的就是将它传递给 callproc。在下一个示例中,我的存储过程称为 sp_test,它需要 4 个参数(最后一个参数是输出参数):

    new_value = self.cursor.callproc('sp_test', (5, 0, 0, counter))
    return new_value[3]
    

    sp_test 的结果是一个数组,其中有 4 个参数传递给存储过程,最后一个参数从中获取值:

    [5, 0, 0, 1463]
    

    由于数组索引从 0 开始,因此您从 new_value[3] 中的存储过程中获取返回值。

    【讨论】:

      猜你喜欢
      • 2022-01-08
      • 1970-01-01
      • 1970-01-01
      • 2023-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多