使用 mssql-python 呼叫儲存程序

mssql-python 驅動程式並未實作 callproc() DB-API 2.0 規範中的方法。 呼叫 callproc() 會引發 NotSupportedError。 相反地,請使用 ODBC {CALL ...} 跳脫序列搭配標準查詢執行方法。

基本的儲存程序執行

無參數

使用 {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() 在它們之間切換:

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 訊息時,請在 execute() 之後讀取 cursor.messages,並在每次呼叫 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}")

此模式適用於任何有身份欄位的資料表,且不需儲存程序。

不支援的功能

callproc()

如果您呼叫 cursor.callproc()mssql-python 驅動程式會引發 NotSupportedError。 如本文所展示的,請使用 cursor.execute("{CALL ...}")cursor.execute("EXECUTE ...") 取代。

表格值參數(TVP)

目前版本(1.11.0) mssql-python不支援表格值參數。 如果你需要將一組列傳給儲存程序,請使用以下替代方案:

  • 先插入暫存資料表,再讓預存程序從該表讀取。
  • bulkcopy() 來載入資料到暫存表。
  • 傳出一個 JSON 字串,然後在程序內用 OPENJSON 解析它。