아래는 Person 의 행을 클릭하면 하단의 “직업이력” “학교”의 정보를 프로시저를 이용해서 한번에 들고 온다.

 

image

 

데이터베이스 구조

imageimage

 

프로시저 만들기(비주얼 스튜디오 2010)

image

image

 

image

실행하기를 클릭하면 파라메터 부분에 임의의 값을 넣어서 프로시저를 확인할 수 있다

image

실행된 상태 (이쁘게 좀 나오지 )

image

 

CS. 코드

코드는 별다른거 없고

NextResult(); 를 이용해서 다음레코드 셋으로 이동한다. 프로시저에서

image 

와 같이 두개의 값을 반환하기 때문이다.

 

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace TestWinForm
{
    public partial class Form1 : Form
    {
        string dbconn = "Data Source=디비위치;Initial Catalog=TEST_DB;Persist Security Info=True;User ID=kojaedoo;Password=비밀번호";
        public Form1()
        {
            InitializeComponent();
        }


        private void Form1_Load(object sender, EventArgs e)
        {
            //기본 Person 가지고 오기
            SqlConnection sqlConnection1 = new SqlConnection(dbconn);
            sqlConnection1.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "SELECT * FROM Person";
            cmd.CommandType = CommandType.Text;
            cmd.Connection = sqlConnection1;
            SqlDataReader rs = cmd.ExecuteReader(CommandBehavior.CloseConnection);

            BindingSource bs = new BindingSource();
            bs.DataSource = rs;
            
            this.dgvPerson.DataSource = bs;

            rs.Close();
            sqlConnection1.Close();
        }



        private void dgvPerson_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            //Person 클릭했을때 첫번째 가져오기
            int PostID = int.Parse(dgvPerson[0, e.RowIndex].Value.ToString());
            //프로시져로 값 다른정보 가져오기
            GetPersonInfo(PostID);

        }

        private void GetPersonInfo( int PersonID )
        {
            //기존 바인딩 날리기
            this.dgvSchool.Rows.Clear();
            this.dgvJob.Rows.Clear();

            SqlConnection sqlConnection1 = new SqlConnection(dbconn);
            sqlConnection1.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "SP_TEST";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add("@PersonID", SqlDbType.Int);            
            cmd.Connection = sqlConnection1;

            cmd.Parameters["@PersonID"].Value = PersonID; //프로시저 파라메터 값

            SqlDataReader rs = cmd.ExecuteReader();
            //Job
            while (rs.Read())
            {
                DataGridViewRowCollection rows = this.dgvJob.Rows;
                rows.Add( rs["JobName"]);

            }           

            rs.NextResult(); //다음레코드로 이동

            //School
            while (rs.Read())
            {              
                DataGridViewRowCollection rows = this.dgvSchool.Rows;
                rows.Add(rs["SchoolName"]);

            }
            sqlConnection1.Close();
        }

    }
}

+ Recent posts