Pages

Wednesday, August 21, 2013

Fetch data from multiple tables using Store procedure

It is another technique to fetch data from multiple tables. At first we have to create one store procedure like below
create procedure fetchdata
as
      begin
            select * from name
            select * from friend
      end


Then we will all this store procedure using ADO.NET code. In below code we are calling store procedure using single SqlCommand object.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WindowsForm
{
    public partial class Form1 : Form
    {
        public Form1()
        {
           
InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
          
        }
        private void button1_Click_1(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection();
           
con.ConnectionString = "Data Source=Nayab\\SQL_INSTANCE2;Initial Catalog=test;Integrated
Security=True";
            con.Open();

            SqlCommand cmd = new SqlCommand();
           
  cmd.CommandText = "fetchdata";
           
  cmd.CommandType = CommandType.StoredProcedure;
           
           cmd.Connection = con;

           SqlDataAdapter ad = new System.Data.SqlClient.SqlDataAdapter();
           
  ad.SelectCommand = cmd;
           DataSet ds = new DataSet();
           
  ad.Fill(ds);

           this.dataGridView1.DataSource = ds.Tables[0];
           this.dataGridView2.DataSource = ds.Tables[1];

        }
        
    }
}



No comments:

Post a Comment