PROGRAMMER DESK

August 25, 2008

PL/SQL Pragma

Filed under: PL/SQL Pragma — vinayhatwal @ 4:53 am
Tags: , ,

PL/SQL Pragma

 

Pragma –

Pragma is nothing but the compiler directive which simply conveys the information to the compiler. Because the Pragma is the complier directive so the processed at compile time not run time.

 

AUTONOMOUS_TRANSACTION Pragma

 

AUTONOMOUS_TRANSACTION Pragma instructs to the compiler to mark a transaction autonomous, or you can independent. An Autonomous transaction is the independent transactions which runs by the another transaction or main transaction. An autonomous transaction suspends the main transaction in which they are calling, do the SQL statements, commit or rollback then according to the user’s need then after completing resume the main transaction.

 

Commit or Rollback only works for the statements which are inside the calling transaction so that they are independent to the main transaction.  It does not share any lock, resources and any commit or rollback dependence with the main transaction.

 

If you are using it with the triggers then unlike normal triggers these autonomous triggers can perform the DDL operation by using the native dynamic SQL. If you set the isolation level of the main transaction to SERIALIZABLE, as follows, changes made by its autonomous transactions are not visible to the main transaction hen it resumes:

 

See, if the main transaction perform the rollback at any save point after the autonomous block then it will not effect the changes made by the autonomous transaction because the autonomous transaction is fully independent from it’s main transaction.

 

 

Limitations –

You can not use the Pragma in the Subprogram that resides in the package. You can only user Pragma in the individual subprogram. You can use Pragma anywhere in the declarative part of the PL/SQL Block but always use it on the top position in the declarative part for readability.

 

 

 

Consider the following block of code –

 

 

– Main Procedure (Caller Procedure)

create or replace procedure MainProc as

begin

 

    update myemployeemaster set employeename=‘vinny’ where employeename=‘Ashish’;

    SimpleProc;      – Calling an ordinary procedure

    rollback;

   

exception

when others then null;

end;

 

– Procedure without Autonomous Transaction Block (Calee Procedure)  

create or replace procedure SimpleProc as

begin

 

    update myemployeemaster set employeename=‘Vikram’ where employeename=‘Pawan Kumar’;

    commit;

   

exception

when others then null;

end;

 

 

 

Explanation-

 

In the above example the MainProc updates the MyEmployeeMaster table and update the name  Ashish to Vinny. But After a SimpleProc call the procedure want to rollback his transaction. But when the SimpleProc procedure called the control of MaiProc goes into the SiimpleProc. In the SimpleProc MyEmployeeMaster is again updating the name Pawan Kumar with the name Vikram and then it commit its transactions. After the completing of SimpleProc the control again goes to the MainProc Procedure and then want to rollback all the changes done by it. But See, The SimpleProc Transaction has already committed the whole transactions. See the effect in the table MyEmployeeMaster, You will see that all the transactions are committed even of the MainProc Procedure.

It happened because the in the both procedure only single transaction is working, both are the part of a single transaction. So If you want to work on different Procedure for different transactions then you can use the Autonomous_Transaction Pragma. This Pragma will direct to the compiler for doing the different Transaction for the block where it defined.

 

Now the following Block of code is modified by using Autonomous_Transaction Pragma –

 

 

– Main Procedure (Caller Procedure)

create or replace procedure MainProc as

begin

 

    update myemployeemaster set employeename=‘Vinay’ where employeename=‘Vikram’;

    AutoProc;      – Calling an ordinary procedure

    rollback;

   

exception

when others then null;

end;

 

– Procedure without Autonomous Transaction Block (Calee Procedure)  

create or replace procedure AutoProc as

pragma autonomous_transaction;

begin

 

    update myemployeemaster set employeename=‘Pawan Kumar’ where employeename=‘vinny’;

    commit;

   

exception

when others then null;

end;

 

 

 

Explanation-

Now consider the about block of code. In this code AutoProc Procedure difines the Pragma Autonomous_Transaction. So that it has a different transaction for this procedure . When a Commit operation is performed then it will only commit those transactions which are rekated to this procedure. And when the control goes back to the MainProc then it will rollback the transactions of the MainProc Procedure. So As a result name vinny in the MyEmployeeMaster is changed with the name Pawan Kumar. But  Vikram has not changed with the Vinay.

August 19, 2008

Oracle Cursors

Filed under: Oracle Cursors — vinayhatwal @ 4:42 am
Tags: , , , ,

ORACLE CURSORS

 

 

Cursors are the work place user by the Oracle engine for its internal processing to save the data returned by the SQL statements. The type of a cursor depends upon the nature of its working. For Example if Oracle Engine open a cursor for its internal processing then it is known as Implicit Cursor and is a cursor defined by the user as a user defined cursor then it is called as Explicit Cursor.

 

 

Implicit Cursors

 

Implicit Cursors are automatically used by the Oracle Engine to store some information regarding the internal processing of the server. Implicit Cursors are automatically created, fetches records and closed by the oracle database server.

 

Basically Internal Cursors are used to table the information about last insert, update, delete or single row select statement.

 

Implicit Cursor Attributes

 

1)       SQL%ISOPEN If the cursor is open then this attribute returns TRUE otherwise returns FALSE. In the case of implicit cursors this attribute always return FALSE because Implicit Cursors are automatically open and the closed by the Oracle Engine.

 

2)       SQL%FOUND – If cursor affects one or more then one row by the SQL statement then this attribute will return TRUE otherwise it will return FALSE.

 

3)       SQL%NOTFOUND – This is opposite to the SQL%FOUND attribute. If the statement will not return any of the value then this attribute will be TRUE otherwise it will by FALSE.

 

4)       SQL%ROWCOUNT – You can count number of affected rows by the last SQL statement by using this attribute.

 

Consider the following block of code-

 

Take the table used in the tutorial Native Dynamic SQL (MyEmployeeMaster).

 

 

CREATE OR REPLACE PROCEDURE demo_imp IS

 row_deleted VARCHAR2(30);

BEGIN

  

        update MYEMPLOYEEMASTER set EMPLOYEENAME=‘Ashish’ where upper(EMPLOYEENAME) like ‘%V%’;

       

       

        IF SQL%ISOPEN THEN

            dbms_output.put_line(‘SQL%FOUND – True’);

        else

            dbms_output.put_line(‘SQL%FOUND – False’);

        END IF;

 

 

        IF SQL%FOUND THEN

            dbms_output.put_line(‘SQL%FOUND – True’);

        else

            dbms_output.put_line(‘SQL%FOUND – False’);

        END IF;

              

            

        IF SQL%NOTFOUND THEN

            dbms_output.put_line(‘SQL%NOTFOUND – True’);

        else

            dbms_output.put_line(‘SQL%NOTFOUND – False’);

        END IF;

         

        dbms_output.put_line(‘SQL%ROWCOUNT – ‘ || SQL%ROWCOUNT || ‘ NO OF ROWS AFFACTED’);

       

END demo_imp;

 

 

 

 

Resule of above procedure –

 

SQL> set serverout on;

SQL>  exec demo_imp;

SQL%FOUND – False

SQL%FOUND – True

SQL%NOTFOUND – False

SQL%ROWCOUNT – 3 NO OF ROWS AFFACTED

 

Explicit Cursors –

 

Explicit Cursors are explicitly used by the user for the data processing. Explicit Cursors are not automatically opens and close by like an Implicit Cursor. It is declare, open and close by the user in the PL/SQL block. Following are the steps to take by the user for using the Explicit Cursors in their PL/SQL block.

 

1)              Declare the cursor in the declaration section with CURSOR keyword.

2)              Open the declared Cursor by using the OPEN keyword.

3)              Fetch the Record from the opened cursor by the FETCH … INTO keywords.

4)              Process the data in the cursor by using the loop by using the LOOP…. END LOOP block.

5)              Fetch the next record and point out the pointer to the next record by using the FETCH…. INTO.

6)             

Close the opened cursor by using the CLOSE keyword.
 
 

 

Explicit Cursor Attributes-

               

1)   SQL%ISOPEN If the cursor is open then this attribute returns TRUE otherwise returns FALSE.

 

2)   SQL%FOUND – If cursor affects one or more then one row by the SQL statement then this attribute will return TRUE otherwise it will return FALSE.

 

3)   SQL%NOTFOUND – This is opposite to the SQL%FOUND attribute. If the statement will not return any of the value then this attribute will be TRUE otherwise it will by FALSE.

 

4)   SQL%ROWCOUNT – You can count number of affected rows by the last SQL statement by using this attribute.

 

Consider the following block of code

 

 

CREATE OR REPLACE PROCEDURE demo_exp IS

 

 cur sys_refcursor;  

 employeeidx number;

 eployeenamex varchar2(20);

BEGIN

  

    open cur for select employeeid, employeename from myemployeemaster;

    fetch cur into employeeidx,eployeenamex ; 

    while cur%found

    loop

        dbms_output.put_line(‘employeeid: ‘ || employeeidx  || ‘—-’ || ‘eployeename: ‘ || eployeenamex );

        fetch cur into employeeidx,eployeenamex ; 

        commit;

    end loop;   

END demo_imp;      

 

<p class=”MsoNormal” style=”text-align:justify;margin:0;”

August 18, 2008

Native Dynamic SQL

Filed under: Native Dynamic SQL — vinayhatwal @ 4:53 am
Tags: , , ,

Native Dynamic SQL

 

Hello friends,

I am again come with new tutorial, Native Dynamic SQL. In this tutorial we will learn –

 

1)   What is Native Dynamic SQL

2)   How it can be used in PL/SQL

3)   Benefits of the Native Dynamic SQL.

 

What is Native Dynamic SQL?

 

Native dynamic SQL is the mechanism where you can dynamically perform the operation on the oracle database schemas. Native dynamic SQL makes your program more flexible in such situations where you don’t know any information about what to do, in advance. Consider the situation where a reporting tool maintain data on daily basis and there are a lot of source table which contain the data on the basis of some parameters and these parameters can also be changed at run time. So what you will do in this situation. Native Dynamic SQL can be used to handle this type of situation.

 

Native Dynamic SQL statement can be built same as a string variable. And also the bind variables can be used with them to improve the performance of the operations. Remember when you perform any of the operation with PL/SQL, PL/SQL automatically convert the variables of the statement to the bind variable to improve the performance of the statement. When you build up such statements with the Native Dynamic SQL then you have to specify the bind variables with the statement, however it is not mandatory. If you will not give the bind variable, PL/SQL will automatically convert them into bind variables but it will give more overhead on the Server.  

 

So, The Native Dynamic SQL statements can be generated at the run time (dynamically).

 

How it can be used in PL/SQL

 

Native Dynamic SQL statements can be executed by using EXECUTE IMMEDIATE statement following by the single quoted varchar variable with SQL statement.

 

 

DECLARE

   str VARCHAR2 (4000);

BEGIN

   str:= ‘DELETE FROM STUDENT_MASTER WHERE STUDENT_ID=1′;

   EXECUTE IMMEDIATE str;

EXCEPTION

   WHEN OTHERS THEN

      NULL;

END;

 

Above example just delete the student with student id =1.

You can also use bind variable with the Native Dynamic SQL for improving the performance of the direct SQL statements.

 

 

Benefits of the Native Dynamic SQL

1)   You can use DDL (CREATE TABLE, DROP TABLE, ALTER TABLE etc) statements and DCL Statements with the PL/SQL block. In PL/SQL these statement can’t be executed statically.

 

2)   By using Native Dynamic SQL statements you can create the SQL statements with using different WHERE clause conditions in a SELECT statement.

 

 

EXECUTE IMMEDIATE The Magic statement to execute Dynamic SQL

 

EXECUTE IMMEDIATE is the statement for executing the SQL statements dynamically in the PL/SQL block or even for executing the PL/SQL block itself.

 

Syntax of Execute immediate -

 

EXECUTE IMMEDIATE dynamic_string

[INTO {define_variable[, define_variable]… | record}]

[USING [IN | OUT | IN OUT] bind_argument

[, [IN | OUT | IN OUT] bind_argument]…]

[{RETURNING | RETURN} INTO bind_argument[, bind_argument]…];

 

Brief Explanation –

 

EXECUTE IMMEDIATE is used to dynamically execute the SQL statement where dynamic_string is the string type variable which contains the Dynamic SQL. INTO clause is used to take the selected values form the query into the defined variables and record is the %ROWTYPE or user defined records. USING clause is used to take IN or OUT bind variables. RETURNING INTO clause is used with the DML statements which have the RETURNING clause with them for returning the affected column value.

 

Consider the following example –

 

CREATE OR REPLACE procedure WEALTHMAKER.MyTest as 

sql1 varchar(4000);

myrefcur sys_refcursor;

employeecodex number;

employeenamex varchar2(20);

salarymonthx varchar2(20);

salaryyearx varchar2(20);

salaryx varchar2(20);

salaryy number;

TYPE RefEmpTyp IS REF CURSOR;

cv RefEmpTyp;

begin

 

    /***************************************************************************************

                                                BLOCK1   -    DCL STATEMENT

   

    ***************************************************************************************/

    – Droping table if exists

    begin

    execute immediate ‘drop table MyEmployeeMaster’;

    exception

        when others then

        null;

    end;

   

    – Droping table if exists

    begin

    execute immediate ‘drop table MyEmployeeSalary’;

    exception

        when others then

        null;

    end;

   

    – Droping view if exists

     begin

    execute immediate ‘drop view MyClientView’;

    exception

        when others then

        null;

    end;

       

    – Creating a master table

    begin

    execute immediate ‘create table MyEmployeeMaster(EmployeeId number,EmployeeName varchar2(20))’;

    exception

        when others then

        null;

    end;

   

    – Creating Detailed Table

    begin

   

    execute immediate ‘create table MyEmployeeSalary(EmployeeId number,Salary varchar2(20),SalaryMonth number,SalaryYear number)’;

    exception

        when others then

        null;

    end;

   

    /******************************************************************************************

                                                BLOCK2  -    DML STATEMENT

   

    ******************************************************************************************/

    – Inserting values in Master Table

    execute immediate ‘insert into MyEmployeeMaster values (1,”Vinay Hatwal”)’;

    execute immediate ‘insert into MyEmployeeMaster values (2,”Piyush Aggrawal”)’;

    execute immediate ‘insert into MyEmployeeMaster values (3,”Vinita Sharma”)’;

    execute immediate ‘insert into MyEmployeeMaster values (4,”Varsha Dhiman”)’;

    execute immediate ‘insert into MyEmployeeMaster values (5,”Pawan Kumar”)’;

   

   

    – Inserting Values in Detailed Table

    execute immediate ‘insert into MyEmployeeSalary values (1,2000,2,2008)’;

    execute immediate ‘insert into MyEmployeeSalary values (1,2000,3,2008)’;

    execute immediate ‘insert into MyEmployeeSalary values (1,2000,4,2008)’;

    execute immediate ‘insert into MyEmployeeSalary values (1,2000,5,2008)’;

    execute immediate ‘insert into MyEmployeeSalary values (2,2000,2,2008)’;

    execute immediate ‘insert into MyEmployeeSalary values (2,2000,3,2008)’;

    execute immediate ‘insert into MyEmployeeSalary values (2,2000,4,2008)’;

    execute immediate ‘insert into MyEmployeeSalary values (2,2000,5,2008)’;

    execute immediate ‘insert into MyEmployeeSalary values (3,2000,2,2008)’;

    execute immediate ‘insert into MyEmployeeSalary values (3,2000,4,2008)’;

  

    commit;

   

   

    /******************************************************************************************

                                                BLOCK3   -    QUERY 

   

    ******************************************************************************************/

    – Creating View for Displaying

    SQL1:= ‘ create or replace view MyClientView as  ;

    SQL1:= SQL1 || ’select m.EmployeeId,m.EmployeeName,s.SALARYMONTH,s.SALARYYEAR,s.SALARY from MyEmployeeSalary s, MyEmployeeMaster m  ;

    SQL1:= SQL1 || ‘where s.EmployeeId(+)=m.EmployeeId and (s.salarymonth=”02” or s.salarymonth is null)  ;

       

    execute immediate sql1;

 

    open cv for ’select * from MyClientView’;

    loop

        fetch cv into employeecodex,employeenamex,salarymonthx,salaryyearx,salaryx;

        EXIT WHEN cv%NOTFOUND;

        dbms_output.PUT_line(employeecodex ||      || employeenamex  ||      || salarymonthx   ||      || salaryyearx   ||      || salaryx);

    end loop;

   

   

    /******************************************************************************************

                                     BLOCK4  -    DML STATEMENT WITH RETURNING INTO VLAUSE

   

    ******************************************************************************************/

    execute immediate ‘update MyEmployeeSalary set salary=50000 where employeeid=1 and salarymonth=2 and salaryyear=2008 returning salary into :2′ returning into salaryy;

    commit;

        dbms_output.PUT_line();

        dbms_output.PUT_line();

        dbms_output.PUT_line(‘Updated Salary—-’ || salaryy);

   

   

    open cv for ’select * from MyClientView’;

    loop

        fetch cv into employeecodex,employeenamex,salarymonthx,salaryyearx,salaryx;

        EXIT WHEN cv%NOTFOUND;

        dbms_output.PUT_line(employeecodex ||      || employeenamex  ||      || salarymonthx   ||      || salaryyearx   ||      || salaryx);

    end loop;

   

exception

    when others then

    dbms_output.put_line(SQLERRM(SQLCODE));

end;

 

 

Brief Explanation –

 

BLOCK 1 – Specifies the DDL statement, some Tables are dropped and Some Tables are created with using the dynamic SQL.

 

BLOCK 2 – Specifies some DML statements which insert values into the table created in the BLOCK 1.

 

BLOCK 3 – View is created to show the data at the run time by using the Implicit Cursor for the Query.

 

BLOCK 4 – Specifies DML statement UPDATE to show the working of RETURNING INTO clause with the EXECUTE IMMEDIATE.

 

 

USING Vs. RETURNING INTO

 

By using OUT parameter with USING clause you can also take the advantage of the RETURNING INTO clause.

Consider the following block of code –

 

 

 

 

CREATE OR REPLACE procedure WEALTHMAKER.UsingVsRETINTO as 

str varchar2(4000);

bsalary number;

bsalary_out number;

bemployeeid number;

bmonth number;

byear number;

begin

 

    bsalary:=40000;

    bemployeeid:=1;

    bmonth:=2;

    byear:=2008;

   

    str:= ‘ update myemployeesalary set salary=:bind_salary where employeeid=:bind_employeeid  ;

    str:= str ||     and salarymonth=:bind_month and salaryyear=:bind_year returning salary into :bindsalaryret ‘;

 

    –Statement 1

    execute immediate str using bsalary,bemployeeid,bmonth,byear,out bsalary_out;

    dbms_output.put_line(bsalary_out);

   

   

    bsalary:=50000;

    –Statement 1

    execute immediate str using bsalary,bemployeeid,bmonth,byear returning into  bsalary_out;

    dbms_output.put_line(bsalary_out);   

 

exception

    when others then

    dbms_output.put_line(SQLERRM(SQLCODE));

end;

 

 

In the above example you can see in Statement 1, the updated salary is taken out into bsalary_out OUT parameter by using the USING clause

 

But in the case of Statement 2, updated salary is taken out by using the RETURNING INTO clause.

 

So, finally you can use any of the statement to return the result of the DML statement.

 

The only difference in these two statements is, with USING clause all the followed parameter are IN mode by default, it means you need not to specify the IN mode for the variable, On the other hand in the case of RETURNING INTO clause all the variables are in the OUT mode by default.

 

 

Using Schema Name with Dynamic SQL

 

Suppose you want to user the Scheme name with the Dynamic SQL then normally you might write the code like the following –

 

CREATE PROCEDURE drop_some_table (tablename IN VARCHAR2) AS

BEGIN

EXECUTE IMMEDIATE ‘DROP TABLE :tab’ USING table_name;

END;

 

But Remember, you will find the error Invalid Table Name because you can’t use bind variables with any schema name. So you should write the following code to debug the above code.

 

CREATE PROCEDURE drop_some_table (tablename IN VARCHAR2) AS

BEGIN

EXECUTE IMMEDIATE ‘DROP TABLE ‘ || table_name;

END;

 

Duplicate Placeholders

 

Placeholders in Dynamic SQL are the elements by which the bind variables are associated with the corresponding item followed by the USING clause. These variables are associated with the values by the position not by the name. So remember the you can use the same name with the placeholders. For examples consider the following line of code:

 

sql_stmt := ’INSERT INTO payroll VALUES (:x, :x , :y, :x )’;

 

it does not matter you are writing the execute stament like this

 

EXECUTE IMMEDIATE sql_stmt USING a, a, b, a;

Or

EXECUTE IMMEDIATE sql_stmt USING a, b, b, a;

August 13, 2008

Crystal Report With .Net

Filed under: Crystal Report With .Net — vinayhatwal @ 6:09 am

Crystal Report with C#.Net 2.0

 

Using Crystal Report is very easy task. Sometime we afraid to use crystal reports with the code of Vb.Net or C#.Net even when we have used crystal reports in the previous technologies like Visual Basic 6. Before writing this tutorial I found some of my friends unable to user crystal report and stuck out in small problems regarding Crystal Report. So I decided to write this tutorial for them and also for those people who are afraid with Crystal Reports and found some difficulties to use it. This tutorial may play a very important role to learn Crystal with Vb.Net/C#.Net for those are new to take crystal with .Net but have used crystal with some of the earlier technologies or who are new even to Crystal.

 

So Friends, Lets Have a look on the tools used in crystal reports with VB.Net/C#.Net.

 

1)      DataSet (System.Data.DataSet)

2)      Crystal Report

3)      CrystalReportViewer1 (CrystalDecisions.Windows.Forms.CrystalReportViewer)

4)      System.Data.SqlClient

 

Now Follow these Steps for the first stage to learn the crystal reports

 

Stage 1 Create Data Base Table (I ussed SqlServer2000)

 

1. Create These Basic Tables using SqlServer2000

 

Create Table DemoStudentMaster

(

            StudentId int primary key,

            StudentName varchar(15),

            StudentAddress varchar(50),

            StudentCity varchar(20),

            StudentMobile varchar(10)

)

 

Create Table StudentFeeDetails

(

            StudentId int references DemoStudentMaster(StudentId),

            SumittedFeeAmt int,

            ForMonth int,

            ForYear int

)

 

2. Insert Values in These Tables

 

DemoStudentMaster

insert into DemoStudentMaster values (1,’Vinay Hatwal’,'Nehru Place’,'New Delhi’,'9911884523′);

insert into DemoStudentMaster values (2,’Panjak Pundir’,'Nehru Place’,'New Delhi’,'7483434356′);

insert into DemoStudentMaster values (3,’Ashish C.’,'Nehru Place’,'New Delhi’,'7473949866′);

insert into DemoStudentMaster values (4,’Sandeep S.’,'Nehru Place’,'New Delhi’,'791198475′);

insert into DemoStudentMaster values (5,’Pradeep K.’,'Nehru Place’,'New Delhi’,'8911884523′);

 

StudentFeeDetails

 

insert into StudentFeeDetails values (1,1000,2,2008);

insert into StudentFeeDetails values (1,1000,3,2008);

insert into StudentFeeDetails values (1,1000,4,2008);

insert into StudentFeeDetails values (1,1000,5,2008);

insert into StudentFeeDetails values (1,1000,6,2008);

insert into StudentFeeDetails values (1,1000,7,2008);

 

 

insert into StudentFeeDetails values (2,4000,2,2008);

insert into StudentFeeDetails values (2,4000,3,2008);

insert into StudentFeeDetails values (2,4000,4,2008);

insert into StudentFeeDetails values (2,4000,5,2008);

insert into StudentFeeDetails values (2,4000,6,2008);

 

 

insert into StudentFeeDetails values (3,3000,2,2008);

insert into StudentFeeDetails values (3,3000,3,2008);

insert into StudentFeeDetails values (3,3000,4,2008);

 

 

insert into StudentFeeDetails values (5,10000,2,2008);

insert into StudentFeeDetails values (5,10000,3,2008);

 

 

Now Your Tables Are Ready To Use in Crystal Report.

 

Stage 2 – Creating Sample Application in .Net

 

  1. Using C#.Net 2.0

 

 

 

a)      Open a new Project with C# names MyDemoCrystalPrj.

 

b)      Open Solution Explorer , Right Click on MyDemoCrystalPrj then click on Add and then click on New Items.

 

c)      Now Select The DataSet. Renamed it as SampleDataSet , Click on Add Button. Now The SampleDataSet.xsd tab will display.

 

 

   d) Right click on the middle of the page and then click on Add and then DataTable, After Clicking on it a Data Table will Appear on screen.

 

 

e)      Now Right Click on DataTable1 and select Rename . Rename id as StudentMasterTable.

f)      After it Right Click on The table and Select Add then Column. Make The Following Column in it.

a.       StudentID

b.      StudentName

c.       StudentAddress

d.      StuentMob

 

g)      Now Again Open Solution Explorer , Right Click on MyDemoCrystalPrj then click on Add and then click on New Items then select Crystal Report. Rename it as MasterCrystalReport.rpt(All the related references will be automatically added in the references)

h)      After Adding Crystal In Project Following Dialog Box Will appear on the screen

 

 

 

 

i)      Select option As a Blank Report and then press OK. Crystal Report will appear and looks like

 

 

j)      Now right click on DataBase Fields in the Field Explorer , Select Database Expert. After selecting it following screen will appear.

      Select Project Data > ADO.NET DataSets > MyDemoCrystalPrj.SampleDataSet

then add it and then click on OK

 

k)      Now Field Explorer will look like

 

l)      Drag then Fields of StudentMasterTable in the detail section of the Crystal Report. You Can also take the heading on the Report Header Section .Right Client On Report Header Section , Select Insert then Select Text Object. Give the Text as Student Detail and format it according to your need. After Inserting all the things your report will look like

 

 

 

m)      Now Open Form1 and Take CrystalReportViewer Form the Crystal Report Strip in the Toolbox.

n)      Now Go To the Coding Window of  Form1 and write the following code.

 

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Data.SqlClient;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

 

namespace MyDemoCrystalPrj

{

    public partial class Form1 : Form

    {

        SqlConnection con;

        DataSet ds;

        public Form1()

        {

            SqlDataAdapter adp;

            con = new SqlConnection(“Server=.;Database=master;Integrated Security=true”);

            ds = new DataSet();

            adp = new SqlDataAdapter(“select StudentId,StudentName,StudentAddress,StudentCity,StudentMobile from DemoStudentMaster”, con);

            adp.Fill(ds, “StudentTable”);

            InitializeComponent();

        }

 

        private void Form1_Load(object sender, EventArgs e)

        {

            MasterCrystalReport cr = new MasterCrystalReport();

            cr.SetDataSource(ds.Tables["StudentTable"].DefaultView);

            crystalReportViewer1.ReportSource = cr;

            crystalReportViewer1.Show();

        }

    }

}

 

o)      Finally Run The Project. Your Crystal Report Will Look Like

 

Note – If you find the helps you for learning the crystal report as a beginner the please write comment on this tutorial or just writ few words on vinayhatwal@gmail.com. I will be back by taking some new tutorial on new technologies soon.

  

Blog at WordPress.com.