簡體   English   中英

使用存儲過程從SQL Server返回數據

[英]Return data from SQL Server using Stored Procedure

我無法使用存儲過程將數據從我的sql-server數據庫返回到aspx頁面,並希望有人可以突出顯示我出錯的地方。

當我運行項目數據成功輸入到表中但在下一頁上沒有返回任何內容(Confirm.aspx)

Confirm.aspx.cs

using Devworks;

namespace OSQARv0._1
{
    public partial class Confirm_Questionnaire : System.Web.UI.Page
    {
        OscarSQL b;

        protected void Page_Load(object sender, EventArgs e)
        {
            b = new OscarSQL();
            string qstname = b.GetQuestionName();
            ReturnQstID.Text = qstname;          

        }// End Page_Load

    } // Emd Class Confirm_Questionnaire

} // End Namespace

SQL.cs(應用代碼)

public OscarSQL()
        {
            _productConn = new SqlConnection();
            _productConnectionString += "data source=mssql.database.co.uk; Initial Catalog=devworks_oscar;User ID=username;Password=password";
            _productConn.ConnectionString = _productConnectionString;
        }
    public string GetQuestionName()
            {
                SqlCommand myCommand = new SqlCommand("GetQuestion", _productConn);
                myCommand.CommandType = CommandType.StoredProcedure;
                SqlParameter retval = myCommand.Parameters.Add("@QUESTTEXT", SqlDbType.VarChar);
                retval.Direction = ParameterDirection.Output;
                _productConn.Open();
                string returnvalue = (string)myCommand.Parameters["@QUESTTEXT"].Value;
                _productConn.Close();
                return returnvalue;
            }

存儲過程

USE [devworks_oscar]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [hgomez].[GetQuestion]  

AS
    /*SET NOCOUNT ON;*/
    SELECT QuestionText FROM [Questions] WHERE QuestionnaireID = 21
    RETURN

任何幫助將非常感激。

你沒有執行proc。 你正在設置它,但沒有返回它。

string returnvalue = (string)myCommand.ExecuteScalar();

您的存儲過程不使用輸出參數來返回值,因此請使用ExecuteScalar()

string returnvalue = (string)myCommand.ExecuteScalar();

返回值是存儲過程返回的值,通常這是一個整數值,有時它用於驅動業務邏輯或錯誤條件。 在您的情況下,您需要返回的數據,而不是返回值。 因此,如果查詢返回單個值,則使用ExecuteScalar;如果查詢返回一個或多個數據記錄,則使用ExecuteReader。 ExecuteNonQuery通常用於插入/更新和/或刪除操作。

ExecuteScalar() is a good idea if you know there is only one occurance of that record in the database, ExecuteScalar if I am not mistaken only returns the first record or occurance it finds.. you could use a datareader and do datareader.ExecuteReader() this is forward only but there are ways to make it biDirectional hehe... :) anyway if you want to loop thru the results use ExecuteReader() if you want to execute a StoredProceduere with UDATE,DELETE, or INSERT use reader.ExecuteNonQuery().

Hope this helps.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM