如何将返回行值或列值的 SQL 存储过程结果存储到 ASP.NET C# 变量中



我有一个返回列值的SQL存储过程(SQL数据类型:nchar(1))。存储过程运行,并在传递参数时返回所需的值。基于这个返回值,我想转移程序流。为此,我需要读取 ASP.NET C# 变量中返回的值,但我不确定如何做到这一点。

create procedure sproc_Type
      @name as nchar(10)
AS    
SELECT Type FROM Table WHERE Name = @name

我想读取Type文件中的值.cs并希望保存它以供以后使用。

             SqlConnection conn = null;
             SqlDataReader rdr  = null;
             conn = new 
                SqlConnection("Server=(local);DataBase=Northwind;Integrated Security=SSPI");
            conn.Open();
            // 1.  create a command object identifying
            //     the stored procedure
            SqlCommand cmd  = new SqlCommand(
                "Stored_PROCEDURE_NAME", conn);
            // 2. set the command object so it knows
            //    to execute a stored procedure
            cmd.CommandType = CommandType.StoredProcedure;
            // 3. add parameter to command, which
            //    will be passed to the stored procedure
            cmd.Parameters.Add(
                new SqlParameter("@PARAMETER_NAME", PARAMETER_VALUE));
            // execute the command
            rdr = cmd.ExecuteReader();
            // iterate through results, printing each to console
            while (rdr.Read())
            {
                var result = rdr["COLUMN_NAME"].ToString();
            }
string connectionString = "(your connection string here)";
string commandText = "usp_YourStoredProc";
using (SqlConnection conn = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand(commandText, conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandTimeout = 600;
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
while(dr.Read())
{
// your code to fetch here.
}
conn.Close();
}

最新更新