在C#中使用預存程序(帶輸入參數)

來源:互聯網
上載者:User

1首先在SQL Server中使用預存程序

CREATE procedure [dbo].[sp_dia] 
@age int, 
@tot int=0 output 
as 
select Sage,Sname 
from Students 
where Sage = @age; 
select @tot = COUNT(*) 
from Students 
where Sage = @age 
return @tot 

2然後建立一個控制台應用程式項目

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace CallSp2
{
    class CallSp2
    {
        static void Main(string[] args)
        {
            SqlConnection conn = new SqlConnection(@"
            server = ./WB_JAMES;
            integrated security = SSPI;
            database = master");
        try
        {
            conn.Open();
            SqlCommand cmd = conn.CreateCommand();
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "sp_dia";
            /////////
            SqlParameter inparm = cmd.Parameters.Add(
                "@age", SqlDbType.Int);
            inparm.Direction = ParameterDirection.Input;
            inparm.Value = 18;
            ///////////
            SqlParameter ouparm = cmd.Parameters.Add(
                "@tot", SqlDbType.Int);
            ouparm.Direction = ParameterDirection.Output;
            ///////////////
            SqlParameter retval = cmd.Parameters.Add(
                "return_value", SqlDbType.Int);
            retval.Direction = ParameterDirection.ReturnValue;
            ///////////
            SqlDataReader rdr=cmd.ExecuteReader();
            while(rdr.Read())
            {
                Console.WriteLine("{0} {1}"
                    , rdr[0].ToString().PadRight(5), rdr[1].ToString());
            }
            rdr.Close();

            /////////
            Console.WriteLine(
                "The output parameter value is {0}",
                cmd.Parameters["@age"].Value);
            ///////////
            Console.WriteLine(
                "The return value is {0}",
                cmd.Parameters["return_value"].Value);
        }
        catch (System.Exception e)
        {
            Console.WriteLine(e.ToString());
        }
        finally
        {
            conn.Close();
        }
        }
    }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.