共用方式為


將參數傳遞至 SQL Server 預存程式

本文介紹從 Visual FoxPro 將參數傳遞至 SQL Server 預存程式的範例。

原始產品版本: Visual FoxPro
原始 KB 編號: 247370

摘要

有兩種方式可以使用 SQLExec 將參數傳遞至預存程式。 在 Visual FoxPro 的所有版本中運作的其中一種方式是將 SQL 命令建置為字串變數。 這個方法的優點是您可以檢查字串,並確切查看您要傳遞至後端的 SQL 命令。

另一種方式是傳遞前面加上問號的 Foxpro 變數,如同在參數化檢視中一樣。 在 Visual FoxPro 5.0 版和更新版本中,這可讓您從傳回為輸出參數的預存程式取得值。

其他相關資訊

執行下列步驟:

  1. 在 SQL Server 中建立兩個預存程式(如需確切步驟,請參閱在線叢書)。 Mysp_ObjectList只會取得 SysObjects 數據表,並傳回您針對數據表中每個記錄傳遞一次的值。 在mysp_GetVersion中,我們會詳細說明尋找伺服器版本的一般程式。 SELECT @@VERSION 通常會以游標中的記錄形式傳回 SQL Server 版本。 在這裡,我們會將該結果指派給預存程式的輸出參數。

    CREATE PROCEDURE mysp_GetVersion @tcVersion Char(200) Output AS 
    SELECT @tcVersion = @@VERSION
    
    CREATE PROCEDURE mysp_ObjectList @tcParm1 CHAR(10) AS
    SELECT @tcParm1, name FROM sysobjects
    
  2. 在 ODBC 系統管理員中建立名為 SPParmTest 的 DSN,其會連結到您建立上述程序的資料庫。

  3. 在 Visual FoxPro 中執行下列程式代碼:

    *!* Error-checking is omitted for the purposes of this sample:
    *!* you should always check the return values from SQL Passthrough calls.
    lnConn = SQLCONNECT("SPParmTest")
    lcParm1 = "ReturnThis"
    lcParm2 = "Then This"*!* This is the first way, involving building a string 
    *!* containing the parameters.
    lcCommand = "exec mysp_ObjectList '" + lcParm1 + "'"
    =SQLEXEC(lnConn, lcCommand)
    BROWSE
    USE
    
    *!* This is the second way, passing the FoxPro variables directly to 
    *!* the SQL command. This will work in 3.0.
    lcCommand = "exec mysp_ObjectList ?lcParm2"
    =SQLEXEC(lnConn, lcCommand)
    BROWSE
    USE
    
    *!* To get a value back from a stored procedure, initialize the
    *!* output variable first. This won't work under 3.0.
    lcVersion = SPACE(200)
    lcCommand = "exec mysp_GetVersion ?@lcVersion" && Note the pass by reference.
    =SQLEXEC(lnConn, lcCommand)?lcVersion 
    
    =SQLDISCONNECT(lnConn) && clean up.