blog

Home / DeveloperSection / Blogs / Save Values in multiple tables at a time using C# and SQL SERVER 2008 R2

Save Values in multiple tables at a time using C# and SQL SERVER 2008 R2

Vijay Shukla14939 12-Dec-2012

In this blog I am creating a C# console application which is Insert Values at a time in multiple tables with SQL SERVER 2008 R2.

Firstly we can two tables in SQL SERVER.

create table childName
(
      f_name varchar(50),
      s_name varchar(50)
)
create table parentName
(
      father_name varchar(50),
      mother_name varchar(50)
)

Now after creating table we can create a Store Procedure Which is use to insert values in multiple tables.

CREATE PROCEDURE familyName(
    @FirstName varchar(50),
    @SecondName varchar(50),
    @FatherName varchar(50),
    @MotherName varchar(50)
 )
AS
    SET NOCOUNT ON;
    insert into dbo.childName values(@FirstName,@SecondName)
    insert into dbo.parentName values(@FatherName,@MotherName)
GO

Store Procedure name is familyName.

After creating the Store Procedure I create a C# console application.

using System;
using System.Data.SqlClient;
class MultipleTable{
   public static void Main(String []args)
   {
      try
      {
      Console.WriteLine();
      Console.Write("First Name:: ");
      string f_name=Console.ReadLine();
      Console.WriteLine();
      Console.Write("Last Name:: ");
      string l_name=Console.ReadLine();
      Console.WriteLine();
      Console.Write("Father Name:: ");
      string Father_name=Console.ReadLine();
      Console.WriteLine();
      Console.Write("Mother Name:: ");
      string Mother_name=Console.ReadLine();
      SqlConnection con = new SqlConnection("Data Source=(local);Initial Catalog=master;Integrated Security=SSPI;User ID=sa;Password=password;");       con.Open();
                  SqlCommand cmd = new SqlCommand("EXEC familyName'" +f_name+ "','" + l_name+ "','" +Father_name+ "','" +Mother_name+ "';",con);                   cmd.ExecuteNonQuery();
                  con.Close();
      Console.WriteLine();
      Console.WriteLine("Save Successfully");
      }
      catch(Exception e)
      {
            Console.Write("Error"+e);
      }
   }
}

After That compile this console application on the Visual Studio command prompt.


Save Values in multiple tables at a time using C# and SQL SERVER 2008 R2

now check your table values saved in your multiple table.

Save Values in multiple tables at a time using C# and SQL SERVER 2008 R2


Updated 18-Sep-2014

Leave Comment

Comments

Liked By