Cursor in MS-SQL Server Stored Procedures

Bangalore: As per your requirement for looping purpose we use cursor in our stored procedures, stored procedures is nothing but a set of queries, If you wont have any other options then only you have to use cursor in your queries because it will affect the normalization of your sql query.

So consider you have 100 employees and you need to generate the payroll  for these 100 employees, so you have write some complex payroll logic and there you want to pass employee id's and it will generate payroll and insert it into a  table.
This kind of situations we need to do operations row by row or employee by employee one employees payroll has generated then next's like that so we will use cursor in that case.


SQL Syntax


/*----Our Code Starts Here ---*/

USE [Tonz] --database name
GO

-- =============================================
-- Author: Tony Tom
-- Create date: 03-06-2013
-- Description: SQL Cursor Example
-- =============================================
ALTER  PROCEDURE [dbo].[USP_CursorTest]  --Stored procedure name

AS
BEGIN
declare @userid varchar(50); --declare one variable to fetch userid's

   declare db_cursor Cursor For -- declare cursor
     select UserID from UserMain 
         open db_cursor  --opening cursor

              Fetch Next from  db_cursor into @userid -- fetching first value

                    while @@FETCH_STATUS=0 -- checking loop exiting condition
                     begin
                          /* -- do your raw by row operation here--*/
                          insert into uname(usename) values(@userid);
                     fetch next from db_cursor into @userid   --fetching next value

                      end
close db_cursor;
End
/*----Our Code Ends Here ---*/

Here we need only one variable in cursor as per your requirements you can take as many variables you want in that particular row to cursor

Simple Registration Form using SQL Server Stored Procedure C# Windows form Apllication

Banaglore: We need to create a Windows form application and on submit button click we need to insert data's into Sql server Db using sql server stored procedure.
So what all the things we need.
Software Requirements.
We need visual studio for form development,SQL Server Management studio for Database operations.
First we will create a Database with name Test. in sql server management studio.
create a table with 5 columns
You can create it Manually or you can run the below script in your SQL SMStudio.

/*Your Code Starts Here*/

USE [Test]
GO

/****** Object:  Table [dbo].[tbl_login]    Script Date: 4/16/2013 12:09:51 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[tbl_login1](
[Id] [int] IDENTITY(1,1) NOT NULL,
[firstname] [varchar](50) NULL,
[lastname] [varchar](50) NULL,
[username] [varchar](50) NULL,
[password] [varchar](50) NULL,
 CONSTRAINT [PK_tbl_login1] PRIMARY KEY CLUSTERED 
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO

/* Code Ends Here */

Here Id is a primary key and its an auto incremental one.
Now we will create a stored procedure for Inserting data's into Table tbl_login.
How to create stored procedure in SQL Server.
Go to your database Inside programability>Storedprocedure> Right Click and create new procedure.

/* Your Code Starts Here */


USE [Test]
GO
/****** Object:  StoredProcedure [dbo].[Registration]    Script Date: 4/16/2013 12:15:17 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <Author,TONY>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
Create PROCEDURE [dbo].[Registration]
@FirstName as varchar(50),
@Lastname as varchar(50),
@UserName as varchar(50),
@password as varchar(50)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

    -- Insert statements for procedure here
Insert into  tbl_login(firstname,lastname,username,password)
values(@FirstName,@Lastname,@UserName,@password)
END

/* Code Ends Here */

Here we have created a sp with name Registration and we are passing 4(firstname,lastname,username,password) Input parameters and Inserting it into tbl_login
and we will call this sp in our Windows Application.

Now our database operation over.

Open visual studio and create a Windows Form Project  with c#.

Design your form like this. 
Add a App.configuration file to your project.
and write this code in your app.config file.

Sql Server Connection String in App.config file.

/* Your code starts here */

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <connectionStrings>
    <add  name="Connectionstring1" 
          connectionString="Data Source=Tonz-Pc; Initial Catalog=Test;Integrated Security=true"  providerName="System.Data.SqlClient"/>
  </connectionStrings>
</configuration>

/* Your code ends here */

here we have declare the connection string with name Connectionstring1, and database name Test

Double click on the submit  button and write this code inside click event
/* Code starts here */
 private void btnSubmit_Click(object sender, EventArgs e)
        {
            string username;
            string password;
            string firstname;
            string lastname;

            username = txtUserName.Text;
            password = txtPassword.Text;
            firstname = txtFirstName.Text;
            lastname = txtLastname.Text;

            Register(firstname, lastname, username, password);
        }

/* code ends here */

We are receiving  firstname, lastname, username, password from Form and setting it into declared variables.
and we are calling the Register Function and passing the 4 values into that

/* Code Starts Here */


  public void Register(string Fname, string Lname, string Uname, string paswd)
        {
            /* Assigning coonection string to 'constring' variable by calling getConnection function */
           string constring= getConnection();

            /* Declaring Connection Variable */
           SqlConnection con = new SqlConnection(constring);

            /* Checking Connection is Opend or not If its not open the Opens */
           if (con.State != ConnectionState.Open)
               con.Open();

            /* Calling Stored Procedure as SqlCommand */
           SqlCommand cmd = new SqlCommand("Registration", con);
           cmd.CommandType = CommandType.StoredProcedure;

            /* Passing Input Parameters with Command */
           cmd.Parameters.AddWithValue("@FirstName", Fname);
           cmd.Parameters["@FirstName"].Direction=ParameterDirection.Input;
           
           cmd.Parameters.AddWithValue("@Lastname",Lname);
           cmd.Parameters["@Lastname"].Direction=ParameterDirection.Input;

           cmd.Parameters.AddWithValue("@UserName",Uname);
           cmd.Parameters["@UserName"].Direction=ParameterDirection.Input;

           cmd.Parameters.AddWithValue("@password",paswd);
           cmd.Parameters["@password"].Direction = ParameterDirection.Input;

            /* Executing Stored Procedure */
           cmd.ExecuteNonQuery();
           con.Close();
            MessageBox.Show("Data Inserted Succesfully");

        }

/* Code Ends Here */

Get Connection function It will return connection String.

/* Code Starts here */


  public static string getConnection()
        {
            /*Reading Connection string from App.config File */
            string constr = ConfigurationManager.ConnectionStrings["Connectionstring1"].ConnectionString;
            return constr;
            //return true;
        }



/* Code Ends here */

You need to Import these References on top of your code additional to the default Libraries


using System.Data.Sql;
using System.Data.SqlClient;
using System.Configuration;

Compile your project and on submit button click you will get "Data Inserted Succesfully" message if its inserted successfully.

If you have any doubts commend to us