Hướng dẫn python execute stored procedure with output parameter - python thực thi thủ tục lưu trữ với tham số đầu ra

Tôi sử dụng pyodbc và sau đó chuyển đổi đối tượng hàng pyodbc thành một danh sách. Hầu hết các câu trả lời cho thấy một truy vấn khai báo các biến là một phần của truy vấn. Nhưng tôi sẽ nghĩ rằng bạn tuyên bố các biến của bạn là một phần của SP, do đó loại bỏ một bước không cần thiết trong Python. Sau đó, trong Python, tất cả những gì bạn phải làm là truyền các tham số để điền vào các biến đó.

Dưới đây là chức năng tôi sử dụng để chuyển đổi đối tượng ROWS PYODBC thành danh sách có thể sử dụng (danh sách) (lưu ý rằng tôi đã nhận thấy PyoDBC đôi khi thêm các không gian theo dõi, vì vậy tôi giải thích cho tôi hoạt động tốt cho tôi):

def convert_pyodbc(pyodbc_lst):
'''Converts pyodbc rows into usable list of lists (each sql row is a list),
   then examines each list for list elements that are strings,
   removes trailing spaces, and returns a usable list.'''
usable_lst = []
for row in pyodbc_lst:
    e = [elem for elem in row]
    usable_lst.append(e)
for i in range(0,len(usable_lst[0])):
    for lst_elem in usable_lst:
        if isinstance(lst_elem[i],str):
            lst_elem[i] = lst_elem[i].rstrip()
return usable_lst

Bây giờ nếu tôi cần chạy một quy trình được lưu trữ từ Python trả về một bộ kết quả, tôi chỉ cần sử dụng:

strtdate = '2022-02-21'
stpdate = '2022-02-22'

conn = mssql_conn('MYDB')
cursor = conn.cursor()

qry = cursor.execute(f"EXEC mystoredprocedure_using_dates 
'{strtdate}','{stpdate}' ")
results = convert_pyodbc(qry.fetchall())

cursor.close()
conn.close()

Và kết quả mẫu mà sau đó tôi lấy và ghi vào bảng tính hoặc w/e:

[[datetime.date(2022, 2, 21), '723521', 'A Team Line 1', 40, 9], 
[datetime.date(2022, 2, 21), '723522', 'A Team Line 2', 15, 10], 
[datetime.date(2022, 2, 21), '723523', 'A Team Line 3', 1, 5], 
[datetime.date(2022, 2, 21), '723686', 'B Team Line 1', 39, 27], 
[datetime.date(2022, 2, 21), '723687', 'B Team Line 2', 12, 14]]

#**********************************************************************
# FILENAME :    CallSPWithInOutParam.c
#
# DESCRIPTION :
#               This example shows how, using SELECT at the end of a stored
#               procedure, the generation of basic return values and output
#               variables, can be implemented in pyodbc.
#
#               Here we want to call a stored procedure that returns a status
#               value, takes one input parameter and returns an output
#               parameter, in the form:
#
#               {? = CALL InOutRet_Params (?, ?)}
#
#               In pyodbc the only option available for returning values is
#               via data generated by a SELECT, which can then be picked up
#               by fetchone() or fetchall(). This example shows how to use
#               this method and returning values other than record sets.
#
# ODBC USAGE :
#

#
#               Connects to Data Source using Data Source Name
#               Creates cursor on the connection
#               Drops and recreates a procedure 'pyFind_Record'
#	        Loops asking user to input a PersonID (until zero or
#               invalid number entered).
#                   Executes the procedure using cursor.execute()
#                   Calls cursor.fetchall() to retrieve any row found
#                   For each row, displays column values
#   	            Returns number of matching records in table
#                   Returns error status
#               Closes and deletes cursor and closed connection
#
#
import pyodbc

# If OUTPUT and RETURN values were properly supported in python, the call
# to the procedure could be {?=CALL pyInOutRecs(?,?)} where parameter 1 is
# a return value, parameter 2 could be input and paramater 3 could be output.
# To do this we have to have the call as {CALL pyInOutRecs(?)} with just
# the input parameter. The RETURN value and the OUTPUT parameters are
# returned in a rowset generated by additional SELECT statements. See below.
# These can then be retrieved using cursor.nextset() follows by
# cursor.fetchone() or cursor.fetchall() for each.
sqlCreateSP="CREATE PROCEDURE pyInOutRet_Params (\
             @pPersonID int) AS \
             DECLARE @MatchingRecs int; \
             DECLARE @RetCode int; \
             SELECT PersonID, FirstName, LastName, Address, City \
             FROM TestTBL1 WHERE PersonID=@pPersonID; \
             SELECT @MatchingRecs=count(*) FROM TestTBL1 WHERE \
             PersonID=@pPersonID; \
             SELECT @MatchingRecs;\
             SET @RetCode=@@ERROR; \
             SELECT @RetCode;"

# Drop Stored Procedure Statement
sqlDropSP="IF EXISTS (SELECT * FROM sys.objects \
           WHERE type='P' AND name='pyInOutRet_Params') \
           DROP PROCEDURE pyInOutRet_Params"

# Call Stored Procedure Statement
sqlExecSP="{call pyInOutRet_Params (?)}"

# Connect to data source
conn=pyodbc.connect('DSN=DATASOURCE', autocommit=True)

# Create cursor associated with connection
cursor=conn.cursor()

print "\nStored Procedure is : pyInOutRet_Params"

# Drop SP if exists
cursor.execute(sqlDropSP)

# Create SP using Create statement
cursor.execute(sqlCreateSP)

# Loop - prompt for record details, insert and get results returned
while 1:

    # Get PersonId to look up
    userInput=raw_input("\nPerson ID : ")

    # Check positive integer entered, quit if
    # negative or not a number
    try:
        id=int(userInput)
    except ValueError:
        id=0
        if userInput != "":
            print "\nSorry, NAN"

    if id<=0:
        quit()

    # Call SP and trap Error if raised
    try:
        cursor.execute(sqlExecSP,id)
    except pyodbc.Error, err:
        print 'Error !!!!! %s' % err

    # Fetch all rowset from execute
    recs=cursor.fetchall()
    if len(recs)==0:
        print "\nRecord not found."
    else:
        # Process each record individually
        for rec in recs:
            print "\nPersonID   : ", rec[0]

            print "First Name : ",          # Comma on end stops new line being output
            if rec[1]!=None:                # None appears for empty column
                print rec[1][0:10]          # Print string from 0 upto 10
            else:
                print "-"                   # Print - for empty column

            print "Last Name  : ",
            if rec[2]!=None:
                print rec[2][0:10]
            else:
                print "-"

            print "Address    : ",
            if rec[3]!=None:
                print rec[3][0:10]
            else:
                print "-"

            print "City       : ",
            if rec[4]!=None:
                print rec[4][0:10]
            else:
                print "-"

    # Get number of matching records - either 1 or 0
    if cursor.nextset()==True:
        for rec in cursor:
            print "\nMatching Records : ", rec[0]

    # And finally, the SQL status code
    if cursor.nextset()==True:
        for rec in cursor:
            print "\nSQL Status : ", rec[0]

print ("\n\nComplete.")

# Close and delete cursor
cursor.close()
del cursor

# Close Connection
conn.close()

Làm thế nào chúng ta có thể gọi thủ tục được lưu trữ với các tham số đầu vào và đầu ra?

Cách dễ dàng là nhấp chuột phải vào quy trình trong SQL Server Management Studio (SSMS), chọn 'Thực hiện quy trình được lưu trữ ... "và thêm các giá trị cho các tham số đầu vào khi được nhắc. SSM sau đó sẽ tạo mã để chạy quy trình trong Một cửa sổ truy vấn mới và thực hiện nó cho bạn.right-click on the procedure in Sql Server Management Studio (SSMS), select 'Execute stored procedure..." and add values for the input parameters as prompted. SSMS will then generate the code to run the procedure in a new query window, and execute it for you.

Chúng ta có thể sử dụng để đầu ra tham số trong thủ tục không?

Các tham số đầu ra trong các quy trình được lưu trữ được sử dụng để trả về một số giá trị hoặc giá trị.Một thủ tục được lưu trữ có thể có bất kỳ số lượng tham số đầu ra.Logic đơn giản là thế này - nếu bạn muốn trả về 1 giá trị thì hãy sử dụng 1 tham số đầu ra, để trả về 5 giá trị, sử dụng 5 tham số đầu ra, cho 10 sử dụng 10, v.v.A Stored Procedure can have any number of output parameters. The simple logic is this — If you want to return 1 value then use 1 output parameter, for returning 5 values use 5 output parameters, for 10 use 10, and so on.

Làm thế nào chúng ta có thể trả về một giá trị trong thủ tục được lưu trữ?

Bạn có thể sử dụng một hoặc nhiều câu lệnh trả lại trong một quy trình được lưu trữ.Tuyên bố trả lại có thể được sử dụng ở bất cứ đâu sau các khối khai báo trong cơ thể SQL-Procedure-body.Để trả về nhiều giá trị đầu ra, các tham số có thể được sử dụng thay thế.Giá trị tham số phải được đặt trước khi câu lệnh trả về chạy.The RETURN statement can be used anywhere after the declaration blocks within the SQL-procedure-body. To return multiple output values, parameters can be used instead. Parameter values must be set before the RETURN statement runs.

Một thủ tục được lưu trữ có thể chấp nhận các tham số?

- [Người hướng dẫn] như các chức năng, các quy trình được lưu trữ có thể bao gồm các tham số đầu vào để thay đổi các hành động mà quy trình được lưu trữ này thực hiện.Không giống như các chức năng và chế độ xem, các quy trình được lưu trữ có thể ghi dữ liệu vào các bảng hiện tại của chúng tôi, thay vì chỉ trả về các giá trị hiện có.stored procedures can include input parameters to alter the actions that these stored procedure performs. Unlike functions and views though, stored procedures can write data to our existing tables, rather than just returning existing values.