Wednesday, December 26, 2012

Selecting Record to using cursor in stored procedure

Following is an example using cursor to fetch record from table and performing action on each row using while loop, also used try catch in this stored procedure


ALTER PROCEDURE [dbo].[Test_Procedure_By_Khalid]
(
      -- Add the parameters for the stored procedure here
      @TableName nvarchar(255),
      @AreaName varchar(50),
      @SysDate DateTime,
      @ReturnCode INT   OUTPUT
)
AS
     
      DECLARE @GraphID NVARCHAR(50)
      DECLARE @PERIOD INT
      DECLARE @MODELKEY NVARCHAR(50)
      DECLARE @ORIGNALDATE NVARCHAR(50)
      DECLARE @DATE INT
      DECLARE @QTY INT
      DECLARE @TOTALQTY INT
      DECLARE @MODELKEYTYPE INT
      DECLARE @SCREENID NVARCHAR(50)
      DECLARE @RetailModelClassificationName NVARCHAR(50)
      DECLARE @SELECTEDAREA varchar(50)
      DECLARE @INF_Cursor INT
      DECLARE @THEMONTH NVARCHAR(6)
      DECLARE @LASTMONTH NVARCHAR(6)
      DECLARE @LASTYEARMONTH NVARCHAR(6)

      --Cursor Definition
      DECLARE     @Cur_TableParm    CURSOR
     
BEGIN TRY
      ----------------------------
      -- Start Transaction --
      ----------------------------
      BEGIN TRANSACTION
-- Set Cursor to select data from Table CPT_TableParm
      SET @Cur_TableParm = CURSOR FAST_FORWARD FOR
SELECT GraphID,ModelKey,AreaName,ModelClassificationName,ScreenID FROM CPT_TableParm
      WHERE TableName = @TableName
      AND ActFcType = 1
     
      -- Executing Cursor to select data from Table CPT_TableParm
      OPEN  @Cur_TableParm
      FETCH NEXT FROM @Cur_TableParm  INTO
             @GraphID, @MODELKEY,@SELECTEDAREA,
 @RetailModelClassificationName,@SCREENID
     
      -- Looping through cursor result   
      WHILE  @@FETCH_STATUS = 0
        BEGIN
           
Print  @SELECTEDAREA+','+cast(@PERIOD as varchar)+'~'+@MODELKEY+'~'+@ORIGNALDATE+'~'+cast(@DATE as varchar)+'~'+cast(@QTY as varchar)+'~'+
                                          cast(@TOTALQTY as varchar)+'~'+@GraphID+'~''3''~'+@SCREENID
                              SET @ReturnCode = 2

        FETCH NEXT FROM @Cur_TableParm  INTO
                                    @GraphID, @MODELKEY,@SELECTEDAREA,
@RetailModelClassificationName,@SCREENID
       END
      -- Closing @Cur_TableParm to select data from CPT_TableParm
      CLOSE       @Cur_TableParm
      DEALLOCATE  @Cur_TableParm

END TRY

BEGIN CATCH
-- Rollback Transaction --
      ROLLBACK TRANSACTION
      -- Reset Cursor State
      BEGIN
            SET @INF_Cursor = CURSOR_STATUS('global','@Cur_TableParm')
            IF @INF_Cursor = -1
            BEGIN
                  DEALLOCATE  @Cur_TableParm    -- Delete Cursor
            END
            ELSE IF @INF_Cursor <> -3
                  BEGIN
                        CLOSE       @Cur_TableParm    -- Close Cursor
                        DEALLOCATE  @Cur_TableParm    -- Delete Cursor
                  END

            PRINT       ERROR_MESSAGE()
      END
      RETURN 999
END CATCH

Tuesday, December 4, 2012

Very Simple Data Access Layer for Three Tire Application

Below code is for very simple Data Access Layer that can be use in three tier application, it also includes the Method used in with Transaction




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

namespace DataAccessLayer
{
    public static class DAcess
    {
        static string constr = "";
        static SqlCommand sqlcom = new SqlCommand();
        static SqlConnection sqlcon = new SqlConnection();
        static SqlDataAdapter sqlda;
        static SqlTransaction SqlTran;
       
        public static void ConnectToDatabase()
        {
            if (sqlcon.State == ConnectionState.Closed)
            {
                constr = ConfigurationManager.ConnectionStrings["ZaaSConString"].ToString();
                sqlcon = new SqlConnection(constr);
                sqlcon.Open();
            }
        }
        public static void DisconnectToDataBase()
        {
            if(sqlcon.State == ConnectionState.Open)
            sqlcon.Close();
        }

        public static DataTable returnDataTable(string Query)
        {
            DataTable dtResult = new DataTable("ResultTable");
            try
            {
                ConnectToDatabase();
                sqlda = new SqlDataAdapter(Query, sqlcon);
                sqlda.Fill(dtResult);
            }
            catch (Exception ex)
            {
            }
            finally
            {
            }
            return dtResult;
        }
        public static DataTable returnDataTableSpecial(string Query)
        {
            DataTable dtResult = new DataTable("ResultTable");
            try
            {
                ConnectToDatabase();
                sqlcom = new SqlCommand(Query, sqlcon, SqlTran);
                sqlda = new SqlDataAdapter(sqlcom);
                sqlda.Fill(dtResult);
            }
            catch (Exception ex)
            {
            }
            finally
            {
            }
            return dtResult;
        }

        public static int ExecuteQuery(string Query)
        {
            int Result = 0;

            try
            {
                ConnectToDatabase();
                sqlcom = new SqlCommand(Query, sqlcon);
                Result = sqlcom.ExecuteNonQuery();
                sqlcon.Close();
            }
            catch (Exception ex)
            {
                sqlcon.Close();
                throw ex;
            }
            finally
            {
                sqlcon.Close();
            }

           
            return Result;
        }
        public static int NewExecuteQuery(string Query)
        {
            int Result = 0;
            sqlcom = new SqlCommand(Query, sqlcon, SqlTran);
            Result = sqlcom.ExecuteNonQuery();
            return Result;
        }
        public static void StartTransaction()
        {
            SqlTran = sqlcon.BeginTransaction(IsolationLevel.ReadUncommitted);
        }
        public static void CommitTransaction()
        {
            SqlTran.Commit();
        }
        public static void RollBackTransaction()
        {
            SqlTran.Rollback();
        }
        public static void CloseTransaction()
        {
            SqlTran.Dispose();
        }
       
       
        public static string returnScalar(string Query)
        {
            string ResultString = "";

            try
            {
                ConnectToDatabase();
                sqlcom = new SqlCommand(Query, sqlcon);
                ResultString = Convert.ToString(sqlcom.ExecuteScalar());
                sqlcon.Close();
            }
            catch (Exception ex)
            {
                sqlcon.Close();
                throw ex;
            }
            finally
            {
                sqlcon.Close();
            }


            return ResultString;
        }
        public static string NewreturnScalar(string Query)
        {
            string ResultString = "";
            sqlcom = new SqlCommand(Query, sqlcon,SqlTran);
            ResultString = Convert.ToString(sqlcom.ExecuteScalar());
            return ResultString;
        }


    }
}