使用 mssql-python 调用存储过程

mssql-python 驱动没有实现 DB-API 2.0 规范中的该 callproc() 方法。 调用 callproc() 会引发 NotSupportedError。 相反,使用ODBC {CALL ...} 转义序列配合标准查询执行方法。 从版本 1.19.0 开始,您可以将表值参数传递给 execute()。 更多信息,请参见 “表值参数”。

存储过程的基本执行

无参数

使用 {CALL} 转义序列来执行存储过程。 本例调用 sp_databases 系统存储过程,该过程不取参数,每个数据库返回一行:

import mssql_python

conn = mssql_python.connect(connection_string)
cursor = conn.cursor()

cursor.execute("{CALL sp_databases}")

for row in cursor:
    print(row.DATABASE_NAME, row.DATABASE_SIZE)

输入参数

使用位置或命名占位符传递参数:

# Single parameter
cursor.execute(
    "{CALL dbo.uspGetManagerEmployees(?)}", (16,)
)

for row in cursor:
    print(row.FirstName, row.LastName)

输出参数

声明并检索输出参数

SQL Server 存储过程可以通过输出参数返回值。 使用 Transact-SQL(T-SQL)变量捕获输出值,然后用以下 SELECT 语句检索:

cursor.execute("""
    DECLARE @total_out MONEY;
    SELECT @total_out = SUM(TotalDue)
    FROM Sales.SalesOrderHeader
    WHERE CustomerID = %(customer_id)s;
    SELECT @total_out AS TotalAmount;
""", {"customer_id": 29825})

row = cursor.fetchone()
total = row.TotalAmount
print(f"Customer total: ${total}")

多个输出参数

通过声明独立变量来捕捉多个输出值。 同样的模式适用于任何具有 OUTPUT 参数的存储过程:

cursor.execute("""
    DECLARE @total_orders INT, @total_spent MONEY;
    SELECT @total_orders = COUNT(*), @total_spent = SUM(TotalDue)
    FROM Sales.SalesOrderHeader
    WHERE CustomerID = %(cust_id)s;
    SELECT @total_orders AS OrderCount, @total_spent AS TotalSpent;
""", {"cust_id": 29825})

stats = cursor.fetchone()
print(f"Orders: {stats.OrderCount}, Total spent: ${stats.TotalSpent}")

返回值

捕获存储过程返回值

执行返回结果的存储过程:

cursor.execute("EXECUTE dbo.uspGetEmployeeManagers @BusinessEntityID = %(emp_id)s", {"emp_id": 5})

rows = cursor.fetchall()
if rows:
    print(f"Found {len(rows)} managers in chain")
    for row in rows:
        print(f"  Manager: {row.FirstName} {row.LastName}")
else:
    print("No managers found")

带输出参数的返回值

cursor.execute("""
    DECLARE @return_value INT, @message NVARCHAR(500);
    SELECT @return_value = CASE WHEN COUNT(*) > 0 THEN 0 ELSE 1 END,
           @message = CASE WHEN COUNT(*) > 0 THEN N'Customer found' ELSE N'Customer not found' END
    FROM Sales.Customer WHERE CustomerID = %(cust_id)s;
    SELECT @return_value AS ReturnCode, @message AS Message;
""", {"cust_id": 29825})

result = cursor.fetchone()
print(f"Return code: {result.ReturnCode}, Message: {result.Message}")

结果集

单一结果集

执行返回单个结果集的存储过程:

cursor.execute(
    "{CALL dbo.uspGetBillOfMaterials(?, ?)}",
    (800, "2026-01-01")
)

customers = cursor.fetchall()
for row in customers:
    print(f"{row.ProductAssemblyID}: {row.ComponentDesc}")

多个结果集

每推进到一个结果时,nextset() 就会刷新 rowcount。 数据修改结果报告其自身的受影响行数,并且具有 description is None;不要对该结果调用提取方法。 产生行的结果在提取前以 rowcount == -1 开始。 SET NOCOUNT ON 抑制受影响行的结果。 关于混合这些结果类型的批次,请参见跟踪批次中的每个结果。

某些存储过程返回多个结果集。 使用 nextset() 在它们之间导航:

cursor.execute("""
    SELECT TOP 1 SalesOrderID, OrderDate, TotalDue
    FROM Sales.SalesOrderHeader WHERE CustomerID = 29825;
    SELECT TOP 3 Name, ListPrice
    FROM Production.Product WHERE ListPrice > 0
    ORDER BY ListPrice DESC;
""")

# First result set: order header
order = cursor.fetchone()
print(f"Order: {order.SalesOrderID}, Date: {order.OrderDate}")

cursor.nextset()

# Second result set: products
print("Products:")
for item in cursor:
    print(f"  {item.Name}: ${item.ListPrice}")

查看更多结果集

使用 nextset() 遍历存储过程返回的所有结果集:

cursor.execute("SELECT TOP 3 ProductID, Name FROM Production.Product; SELECT TOP 3 FirstName, LastName FROM Person.Person")

result_set_num = 1
while True:
    print(f"--- Result Set {result_set_num} ---")
    for row in cursor:
        print(row)
    
    if not cursor.nextset():
        break
    result_set_num += 1

涉及存储过程的事务

显式交易控制

在事务中包装多个存储过程调用以确保原子性:

conn.autocommit = False

try:
    cursor.execute("{CALL dbo.DebitAccount(?, ?)}", (1001, 100.00))
    
    cursor.execute("{CALL dbo.CreditAccount(?, ?)}", (1002, 100.00))
    
    conn.commit()
    print("Transfer completed")
except mssql_python.DatabaseError as e:
    conn.rollback()
    print(f"Transfer failed: {e}")

让存储过程管理事务

如果存储过程处理自己的事务:

conn.autocommit = True  # Let SP manage transactions

cursor.execute("""
    DECLARE @result INT;
    EXECUTE @result = dbo.TransferFunds 
        @FromAccount = %(from_acc)s,
        @ToAccount = %(to_acc)s,
        @Amount = %(amount)s;
    SELECT @result AS TransferResult;
""", {"from_acc": 1001, "to_acc": 1002, "amount": 100.00})

result = cursor.fetchone()
if result.TransferResult == 0:
    print("Transfer successful")

错误处理

捕获存储过程错误

处理由存储过程或 Transact-SQL 语句引发的异常:

try:
    cursor.execute("{CALL dbo.DangerousProcedure}")
except mssql_python.ProgrammingError as e:
    # Handle SQL errors raised by RAISERROR or THROW
    print(f"Stored procedure error: {e}")
except mssql_python.DatabaseError as e:
    # Handle other database errors
    print(f"Database error: {e}")

捕获 PRINT 语句和信息性消息

SQL Server PRINT 语句和严重性级别低于 11 的 RAISERROR 会在执行后捕获到 cursor.messages 中。 每个条目均为一个 (message_type, message_text) 元组。 当 PRINT 在结果集之前运行时,它会先占用一个不包含任何行的结果集,因此应先读取 cursor.messages,然后调用 nextset() 以访问这些行:

cursor.execute("PRINT 'Operation complete'; SELECT 1 AS Status")

for msg_type, msg_text in cursor.messages:
    print(f"Server message: {msg_text}")

cursor.nextset()
row = cursor.fetchone()
print(f"Status: {row.Status}")

当存储过程跨多个结果集发出 PRINT 消息时,请在 cursor.messages 之后读取 execute(),并在每次调用 nextset() 后再次读取,以捕获每个结果集中的消息:

cursor.execute("""
    PRINT 'Starting first result set';
    SELECT TOP 3 ProductID, Name FROM Production.Product;
    PRINT 'Starting second result set';
    SELECT TOP 3 FirstName, LastName FROM Person.Person;
""")

all_messages = []
while True:
    all_messages.extend(cursor.messages)
    if cursor.description:
        for row in cursor:
            print(row)
    if not cursor.nextset():
        break

for _, text in all_messages:
    print(f"Server: {text}")

完整 cursor.messages API 请参见 光标管理。

最佳做法

使用命名参数

命名参数更清晰,且保持顺序独立性:

# Recommended: {CALL} with positional parameters
cursor.execute(
    "{CALL dbo.uspGetBillOfMaterials(?, ?)}",
    (800, "2026-01-01")
)

# Also valid: EXECUTE with named T-SQL parameters
cursor.execute("""
    EXECUTE dbo.uspGetBillOfMaterials
        @StartProductID = ?,
        @CheckDate = ?
""", (800, "2026-01-01"))

处理可空的输出参数

从存储过程获取输出参数时,检查是否为 NULL:

cursor.execute("""
    DECLARE @optional_value NVARCHAR(100);
    SELECT @optional_value = Color FROM Production.Product WHERE ProductID = %(id)s;
    SELECT @optional_value AS OutputValue;
""", {"id": 1})

result = cursor.fetchone()
if result.OutputValue is not None:
    print(f"Value: {result.OutputValue}")
else:
    print("No value returned")

在存储过程中使用 SET NOCOUNT ON

为了提升性能和更干净的结果处理,确保你的存储过程包括:

CREATE PROCEDURE dbo.MyProcedure
AS
BEGIN
    SET NOCOUNT ON;  -- Prevents "n rows affected" messages
    -- procedure logic
END

示例:完整工作流程

这里有一个实际的例子,可以调用存储过程,检索输出值并处理错误:

import mssql_python

def get_employee_report(manager_id: int) -> dict:
    """Look up a manager's employees and compute average vacation hours."""
    conn = mssql_python.connect(connection_string)
    conn.autocommit = False
    cursor = conn.cursor()

    try:
        # Get manager info
        cursor.execute("""
            SELECT BusinessEntityID, JobTitle
            FROM HumanResources.Employee
            WHERE BusinessEntityID = %(mgr)s
        """, {"mgr": manager_id})
        mgr = cursor.fetchone()
        print(f"Manager {mgr.BusinessEntityID}: {mgr.JobTitle}")

        # Get direct reports via stored procedure
        cursor.execute("{CALL dbo.uspGetManagerEmployees(?)}", (manager_id,))
        employees = cursor.fetchall()
        print(f"Found {len(employees)} employee(s)")

        # Compute average vacation hours
        cursor.execute("""
            DECLARE @avg_hours INT;
            SELECT @avg_hours = AVG(VacationHours)
            FROM HumanResources.Employee;
            SELECT @avg_hours AS AvgVacation;
        """)
        avg = cursor.fetchone().AvgVacation
        print(f"Avg vacation hours: {avg}")

        conn.commit()
        return {"manager": mgr.JobTitle, "reports": len(employees), "avg_vacation": avg}

    except mssql_python.DatabaseError as e:
        conn.rollback()
        raise
    finally:
        cursor.close()
        conn.close()

# Usage
result = get_employee_report(manager_id=16)

使用 OUTPUT INSERTED 获取生成的键值

要从 INSERT (有无存储过程)中检索身份值,可以用 OUTPUT INSERTED 代替 SCOPE_IDENTITY()。 这种方法在同一结果集中返回该值:

cursor.execute("""
    INSERT INTO Production.ProductCategory (Name)
    OUTPUT INSERTED.ProductCategoryID
    VALUES (%(name)s)
""", {"name": "Custom Parts"})

new_id = cursor.fetchval()
print(f"New category ID: {new_id}")

这种模式适用于任何带有身份列的表,且不需要存储过程。

表值参数

从版本 1.19.0 开始,通过将一组行包装在 TableValuedParameter(type_name, columns, rows, *, schema=None) 中,并将该对象传递给 execute(),即可将其作为表值参数传递。 驱动程序不会将普通的列表列表或元组列表视为表值参数。

在服务器上声明表类型和 READONLY 参数:

CREATE TYPE dbo.ItemBatch AS TABLE (id INT, label NVARCHAR(100));
GO

CREATE PROCEDURE dbo.ProcessItems @items dbo.ItemBatch READONLY
AS
SELECT id, label FROM @items;

传递来自 Python 的行:

from mssql_python import SQL_INTEGER, SQL_WVARCHAR, TableValuedParameter

items = TableValuedParameter(
    type_name="dbo.ItemBatch",
    columns=[("id", SQL_INTEGER), ("label", SQL_WVARCHAR, 100)],
    rows=[(1, "Keyboard"), (2, None)],
)

cursor.execute("EXECUTE dbo.ProcessItems ?", (items,))

for row in cursor:
    print(row.id, row.label)

将每列定义为一个 (name, sql_type[, size_or_precision[, scale]]) 元组,并使用驱动程序的 SQL_* 常量:

  • 驱动按位置绑定列。 列名仅出现在错误信息中。 驱动程序不会在服务器上查找表类型。
  • 字符列和二进制列需要一个大小。 对于可变长度类型,0 表示 MAX。 Unicode 大小以 UTF-16 码单元表示,二进制大小以字节为单位。
  • 十进制和数值列既需要精度,也需要小数位数,例如 ("amount", SQL_DECIMAL, 20, 6)。 精度为 1 到 38,小数位数为 0 到精度值。
  • 时间列和日期时间列的小数位数默认为 7。

将类型指定为不带引号的 schema.Type 类型,或传入类型名称和 schema 关键字参数。 默认模式为 dbo。 驱动程序不接受方括号、引号或数据库限定名称。

每一行必须是一个列表或元组,其中每一列都有一个值。 一个值可以是 None。 对于空表,传递 rows=[]。 传入 rows=None 会引发 TypeError。

rows 也可以是迭代器或生成器。 驱动程序在 execute() 期间读取它,并一次持有一行,最多可读取 2,147,483,647 行。 迭代器只能读取一次,发生失败时,迭代器可能只被部分消耗。

一个语句可以将多个表值参数与标量参数及命名参数结合起来。 这些情景会引发 NotSupportedError:

  • executemany()(使用表值参数)
  • setinputsizes(),用于具有表值参数的语句。
  • mssql-odbc 提供程序。 使用默认 msodbcsql18 提供者。

本地异步 API 不接受表值参数。

不支持的功能

callproc()

如果调用 mssql-python,NotSupportedError 驱动程序会引发 cursor.callproc()。 使用 cursor.execute("{CALL ...}") 或 cursor.execute("EXECUTE ...") 替代,正如本文所展示的。