Thursday, 28 February 2013

Finding the 2 nd Highest salary in Sql server


USE Mydb
GO

--creating the table

CREATE TABLE EMP
(
ID INT IDENTITY(1,1)
CONSTRAINT PK_EMP_ID  PRIMARY KEY,
NAME VARCHAR(30) NOT NULL,
SALARY MONEY
)
------To view the structure of the table


SELECT * FROM EMP











----Insert the records into the table

INSERT INTO EMP VALUES ('PRAMOD',12000),
('HARISH',15000),
('NARENDRA',20000),
('KRISHNA',15000),
('KIRAN',23000),
('RAMU',16000)

----FINDING THE TOP 2 nd Highest salary 
SELECT TOP 1  *
FROM EMP WHERE SALARY IN( SELECT TOP 2 SALARY
FROM EMP
ORDER BY 1 DESC)
ORDER BY SALARY asc














-----TOP 4 TH SALARY 

SELECT TOP 1  *
FROM EMP WHERE SALARY IN( SELECT TOP 4 SALARY
FROM EMP
ORDER BY 1 DESC)
ORDER BY SALARY asc




Wednesday, 27 February 2013

JOINS



Joins: by using the join ,we can retrieve the data from two or more tables based on logical relationships
between the tables.


The joins allow you to view data from related tables in a single result set.we can join the more
 then one table based on a common attribute


     depending on the requirements to view data from multiple tables,we can apply the different types of joins,such
     as inner join,outer join,cross join,self join

INNER JOIN:
------------  

        An inner join retrieves the records from multiple tables after comparing the values present in a common column.when inner
join is applied ,only the rows which values satisfying the join condition  in the common column are displayed.
The rows in both the tables that do not satisfy the join condition are not displayed.

 ex:   SELECT EMP.EMPID,EMP.NAME,EMP.SAL,EPH.PHONE_NUM
FROM EMPLOYEE EMP
JOIN EMP_PHONE_NUM EPH
ON EMP.EMPID=EPH.EMPID

OUTER JOIN:
-----------

An outer join displays the result set containing all the rows from one table and matching rows from the other table.


 for example.if we create an outer join on table A and table B ,it will show you all the records of table A and only
those records from table B for which the condition on the common column holds true..


An outer join displays NULL for the columns of the related table where it does not find any matching records .
AN outer join is the following types:
1.Left outer join.
2.Right outer join.
3.Full outer join.

1.LEFT OUTER JOIN:
-------------------
THE LEFT outer join returns the all the rows from the table specified on the left side of the LEFT OUTER JOIN
keyword and the matching rows from  the table specified on the right side .it displays NULL  for the columns of the
 table specified on the right side where it does not find any matching records


EX:SELECT EMP.EMPID,EMP.NAME,EMP.SAL,EPH.PHONE_NUM
FROM EMPLOYEE EMP
LEFT OUTER JOIN EMP_PHONE_NUM EPH
ON EMP.EMPID=EPH.EMPID

2.RIGHT OUTER JOIN:
-------------------
  THE right outer join returns the all the rows from the table specified on the right side of the RIGHT OUTER JOIN
keyword and the matching rows from  the table specified on the left side .it displays NULL  for the columns of the
 table specified on the left side where it does not find any matching records


ex: SELECT EMP.EMPID,EMP.NAME,EMP.SAL,EPH.PHONE_NUM
FROM EMPLOYEE EMP
RIGHT OUTER JOIN EMP_PHONE_NUM EPH
ON EMP.EMPID=EPH.EMPID

 

 3.FULL OUTER JOIN:
-------------------
A full outer join is the combination of left outer join and right outer join.This join returns all the matching and
non-matching rows from the both the tables.
the matching records are displayed only once .In case of non-matching rows,a NULL value is displayed
for the columns for the columns for which data is not available.




ex:SELECT EMP.EMPID,EMP.NAME,EMP.SAL,EPH.PHONE_NUM
FROM EMPLOYEE EMP
FULL OUTER JOIN EMP_PHONE_NUM EPH
ON EMP.EMPID=EPH.EMPID

CROSS JOIN: A cross join is also known as a Cartesian Product .it join each row of one table with each row of the other table


      The number of rows in the result set equal to the number of rows in the first table multiplied by the number of rows
in the second table


ex:SELECT A.NAME,A.SAL,B.PHONE_NUM
FROM EMPLOYEE A
CROSS JOIN EMP_PHONE_NUM B


SELF-JOIN:  A self join, a table is  joined with itself .As a result,one row in the table correlates with other rows in the
---------   same table.


ex:SELECT E.ID,E.NAME,D.DEPT_NO
FROM EMP E
JOIN EMP D
ON E.ID=D.ID






----------------------------------------------------------



                     

Tuesday, 26 February 2013

PRINT THE DIV USING THE JAVA SCRIPT



<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default8.aspx.cs" Inherits="Default8" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <script type="text/javascript">
        function PrintDiv() {
            var divToPrint = document.getElementById('divToPrint');
            var popupWin = window.open('', '_blank', 'width=300,height=300');
            popupWin.document.open();
            popupWin.document.write('<html><body onload="window.print()">' + divToPrint.innerHTML + '</html>');
            popupWin.document.close();
        }
    </script>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div id="divToPrint">
        <h1>
            hai i am printing the Div
        </h1>
    </div>
    <div>
        <input type="button" value="print" onclick="PrintDiv()" />
    </div>
    </form>
</body>
</html>

Monday, 25 February 2013

STORED PROCEDURES



Stored procedure:
------------------
Stored procedures are special objects available in sql server. Its a precompiled statements where all
the preliminary parsing operations are performed and the statements are ready for execution.

Its very fast when compared to ordinary sql statements where the sql statements will undergone a sequence of steps to
fetch the data

Stored procedure involves various syntax based on the parameters passed.
Let me show you a generic syntax for a stored procedure.



create procedure proc_name
as
begin

sql statement1
sql statement2
end


ex:2

create procudere getempproc
as
begin
select * from employee

end




creating the parameterized stored procedures:
---------------------------------------------

we want to execute a procedure for a different values of a variable that are provided
at run time.for this we can create the parameterized stored procedures


the parameters are used to pass values to the stored procedure during run time.


USE  test1
GO

IF EXISTS (SELECT 1 FROM SYS.OBJECTS WHERE [TYPE] = 'P' AND NAME = 'GetMarks')

DROP PROCEDURE GetMarks

GO

CREATE PROCEDURE GetMarks

(

@m1 int=0,

@m2 int=0,

@m3 int=0,

@m4 int=0,

@m5 int=0,

@m6 int=0

)
AS
BEGIN

DECLARE @Tot INT,
DECLARE @Avg FLOAT,

SELECT @Tot = @m1+@m2+@m3+@m4+@m5+@m6,
@avg=@Tot/6
if(@m1>=35&& @m2>=35&& @m3>=35&& @m4>=35 && @m5>=35 && @m6>=35)
BEGIN
PRINT 'pass'
if(@avg>=90)
PRINT 'first division'
else


if(@avg>=75)
PRINT 'second division '
else

if(@avg>=35)

PRINT 'third division '
else

PRINT 'fail'

END
END


by  ushing the stored procedure we can insert the elements into the table
ex:


TABLE1:


IF NOT EXISTS(SELECT * FROM SYS.OBJECTS WHERE name = 'Student_Detail' AND [type] = 'U')
BEGIN
CREATE TABLE Student_Detail
(
StudentId INT IDENTITY(1,1)
CONSTRAINT [PK_Student_Detail_StudentId] PRIMARY KEY,
FirstName VARCHAR(75) NOT NULL,
LastName VARCHAR(25) NOT NULL,
DOB DATETIME NOT NULL,
)
END
GO

TABLE2:


IF NOT EXISTS(SELECT * FROM SYS.OBJECTS WHERE name = 'Cource' AND [type] = 'U')
BEGIN  
CREATE TABLE Cource
(
CourceId int IDENTITY(100,10)
CONSTRAINT [PK_Cource_CourceId] PRIMARY KEY,
Cource_Code VARCHAR(10) ,
CourceName VARCHAR(25) NOT NULL

)

END

TABLE3:


IF NOT EXISTS(SELECT * FROM SYS.OBJECTS WHERE name = 'CITY' AND [type] = 'U')
BEGIN
CREATE TABLE CITY
(CityId INT IDENTITY(600,1)
CONSTRAINT [PK_CITY_CityId] PRIMARY KEY,
CityCode VARCHAR(10) ,
CityName VARCHAR(50))
END







TABLE4:


IF NOT EXISTS(SELECT * FROM SYS.OBJECTS WHERE name = 'STUDENT_CITY' AND [type] = 'U')
BEGIN
CREATE TABLE STUDENT_CITY
(
StudentCityId INT IDENTITY(111,110)
                CONSTRAINT PK_STUDENT_CITY_StudentCityId PRIMARY KEY,
                StudentId INT
                                     CONSTRAINT [FK_STUDENT_CITY_StudentId]  FOREIGN KEY(StudentId)            REFERENCES Student_Detail(StudentId),
CityId INT CONSTRAINT FK_STUDENT_CITY_CityId FOREIGN KEY(CityId)
REFERENCES CITY(CityId)

)
END

TABLE5:



IF NOT EXISTS(SELECT * FROM SYS.OBJECTS WHERE name = 'STUDENT_COURCE' AND [type] = 'U')
BEGIN
CREATE TABLE STUDENT_COURCE
(
StudentCourceId INT IDENTITY(1,1)
CONSTRAINT PK_STUDENT_COURCE_StudentCourceId PRIMARY KEY,
StudentId INT CONSTRAINT [FK_STUDENT_COURCE_StudentId] FOREIGN KEY(StudentId) REFERENCES Student_Detail(StudentId),
CourceId INT CONSTRAINT  [FK_STUDENT_COURCE_courceId] FOREIGN KEY (CourceId) REFERENCES Cource(CourceId)
)


END

HERE FIVE TABLES ARE THERE BY USHING THE STORED PROC WE WILL UPDATE THE ALL THE TABLES



Use VENKAT
GO

IF EXISTS (SELECT 1 FROM SYS.OBJECTS WHERE [TYPE] = 'P' AND NAME = 'SetStudentDetails')
DROP PROCEDURE SetStudentDetails

CREATE  PROCEDURE SetStudentDetails     
(
@firstname VARCHAR(75),
@lastname VARCHAR(25),
@dob DATETIME,
@cource VARCHAR(25),          
@city VARCHAR(50)
)
 
AS
/*******************************************************
CREATED BY :
CREATED DATE : 5//2012
DESC : procedure to SetStudentDetails   
CHANGE HISTORY
NAME DATE DESC

USAGE:
EXEC SetStudentDetails 'NARI','A','1989-03-15','MBA','KHAMMAM'

********************************************************/
SET NOCOUNT ON
BEGIN
DECLARE @StudentIdentity INT
IF NOT EXISTS(SELECT * FROM Student_Detail WHERE  FirstName = @firstname AND LastName = @lastname AND DOB = @dob)
INSERT INTO Student_Detail(
FirstName,
LastName,
DOB
)
VALUES
(
@firstname,
@lastname,
@dob
)
SELECT @StudentIdentity = @@IDENTITY
DECLARE @CourceIdentity INT, @CityIdentity INT
IF NOT EXISTS(SELECT * FROM Cource WHERE  CourceName= @cource)

INSERT INTO Cource
(
Cource_Code,
CourceName
)
VALUES
(
Left (@cource,3),
@cource
)

SELECT @CourceIdentity = CourceId  FROM Cource WHERE  CourceName= @cource
IF NOT EXISTS(SELECT * FROM CITY WHERE CityName = @city)

INSERT INTO  CITY
(
CityCode,
CityName
)
VALUES
(
Left(@city, 4),
@city
)

SELECT @CityIdentity = CityID FROM CITY WHERE CityName = @city
IF NOT EXISTS(SELECT * FROM student_cource WHERE StudentId =@StudentIdentity )

INSERT INTO student_cource
(
StudentId,
CourceId 
)
vALUES
(
@StudentIdentity,
@CourceIdentity                     
)

DECLARE @StudentCourceId INT 
SELECT @StudentCourceId = @@IDENTITY
IF NOT EXISTS(SELECT * FROM STUDENT_CITY WHERE StudentId=@StudentIdentity )
INSERT INTO STUDENT_CITY
(

StudentId,
CITYID
)
vALUES
(

@StudentIdentity,
@CITYIdentity
)

END






EX2:



USE VENKAT
GO


IF EXISTS(SELECT * FROM SYS.OBJECTS WHERE TYPE='P' AND NAME='GetStudentDetails')
DROP PROCEDURE GetStudentDetails
GO


CREATE PROCEDURE GetStudentDetails
(
@StudentID INT
)
AS
/*******************************************
Author    : 
Date      : 05/01/2012
Desc      : Procedure to get Student Details
Usage     : EXEC GetStudentDetails 1
Change History :
Name        Date         Description

********************************************/
SET NOCOUNT ON
BEGIN
IF EXISTS(SELECT * FROM Student_Detail WHERE StudentID = @STUDENTID)
SELECT SD.StudentID,
SD.FirstName,
SD.LastName,
SD.DOB,
CR.CourceId,
CR.Cource_Code,
CR.CourceName,
C.CityID,
C.CityCode,
C.CityName
FROM Student_Detail SD
INNER JOIN Student_City SC
ON SC.StudentID = SD.StudentID
INNER JOIN City C
ON C.CityID = SC.CityID
INNER JOIN STUDENT_COURCE SCR
ON SCR.StudentID = SD.StudentID
INNER JOIN Cource CR
ON CR.CourceId = SCR.CourceId
WHERE SD.StudentID = @StudentID

ELSE
BEGIN
PRINT 'THIS ID IS NOT EXISTS...THERE IS NO STUDENT' 
END

END










DATA TYPES IN SQL


DATA TYPES:
-----------
Data type represent the type of the data that a database object contain.
this data can be in the form of charecters or numbers.


INT
---
stores  onley the integer data
(whole numbers)


range: 2^31-1(2,147,483,647)



smallint:
---------
stores onley the integer values

range:2^15-1(32,767)



money:
-----
stores onley the money data

range:922,337,203,685,477.5808 to 922,337,203,685,477.5807



Datetime:
---------

stores  onley date and time data

range:
january 1,1753 through december 31,9999

time:
----
it accepts onley the Time data

range: 00:00:00:000000 through
23:59:59:9999999


char(n):
--------
it accepts 'n' charecters ,where n can be 1 to 8000
fixed  lengh charecter data

varchar(n)
-----------
it is used to store Variable length character data

n charecters,where n can be 1 to 8000

BINARY:
------
It is used to store Fixed length binary data

maximum length of 8000 bytes


Varbinary:
----------
It is used to store  variable length binary data

maximum length of 8000 bytes.

nvarchar:
---------
it is used to store the variable length Unicode data

max length of 4000 charecters.
©chantidodda

VIEWS


VIEW:

A View is a "Virtual Table". It is not like a simple table, but is a virtual table which contains columns and data from
different tables

A View does not contain any data, it is a set of queries that are applied to one or more tables that is stored within the
database as an object. After creating a view from some table(s),it used as a reference of those tables and when executed,
it shows only those data which are already mentioned in the query during the creation of the View.


view ensure the security of data by restiricting access to:
-specific rows of a table.
-specific rows and columns of a table.
-rows fetched by using join
-specific rows and columns of a table.


we can create the VIEW by using the CREATE VIEW  statement .

ex:
CREATE VIEW EMPVIEW

AS

SELECT E.ID,E.NAME,E.SAL,A.BRANCH_NAME,A.BRANCH_ID

FROM EMP E JOIN DEPARTMENT A

ON E.DEPT_NO=A.BRANCH_ID


GUIDELINES FOR CREATING VIEWS:
------------------------------
->The name of a view must follow the rules for identifies and must not be the same as that of the table on which it is based
->a view can not derive its data from temporary tables.
->in view ORDER BY cannot be used in SELECT statement .


Restrictions at the time of modyfying data through VIEWS:
View do  not maintain the saparate copy the data ,but onley display the data present in the base tables.so we can modyfy the
base tables by modyfying the data in the view.

->we cannot modify the data in a view if the modification affects onley one table at a time.
->we can not change a column that is the result of calculation,such as a computed column or aggregate function.

ALTERING VIEWS
--------------

ALTER VIEW view_name
AS
select statements

RENAMING THE VIEW:
-----------------

SP_RENAME OLD_VIEWNAME,NEW_VIEWNAME

DROPING THE VIEW:
----------------
DROP VIEW VIEW_NAME

EX:



use venkat
go



CREATE TABLE V_DEPT
     (
BranchId  INT IDENTITY(1,1)
                             CONSTRAINT PK_V_DEPT_BranchId  PRIMARY KEY,
BranchName VARCHAR(25) NOT NULL
)

CREATE TABLE V_STUDENT
(
StudentId int IDENTITY(101,1),
StudentName VARCHAR(20) NOT NULL,
BranchName varchar(25) NOT NULL,
BranchId INT NOT NULL
CONSTRAINT [FK_ V_STUDENT_BranchId] FOREIGN KEY(BranchId) REFERENCES V_DEPT(BranchId)
)

----INSERTING THE ELEMENTS INTO THE TABLES----
INSERT INTO V_DEPT(BranchName)
VALUES('CSE'),
('IT'),
('ECE'),
('EEE'),
('MECH')


INSERT INTO V_STUDENT(StudentName,BranchName,BranchId)
VALUES('MUNNA', 'IT' ,2),
('ASHOK', 'ECE' ,3),
('HANEEF', 'EEE',4),
('ASWIN','CSE',1),
('MANOJ','CSE',1),
('ANU','IT',2),
('KRANTHI','ECE',3),
('KANTH','EEE',4)

------------
SELECT * FROM V_DEPT
SELECT * FROM V_STUDENT



-----CREATING THE VIEW----

CREATE VIEW STDVIEW1
AS
SELECT StudentName,
BranchName
FROM V_STUDENT





------UPDATE THE TABLE V_STUDENT---
UPDATE V_STUDENT SET StudentName='rajum'
WHERE StudentId=101

----UPDATE THE VIEW-----

UPDATE STDVIEW1 SET BranchName='IT'
WHERE StudentName='raju'






 
©chantidodda

TRIGGER


Trigger:
--------
A trigger is a set of T-SQL statements activated in response to certion actions,such as insert or delete or update.
triggers are used to ensure data integrity before or after performing the data maniplations
therefore trigger is a special kind of stored procedure that executes in response to specific events.

Whenever the Trigger is fired in response to the INSERT,DELETE OR UPDATE statement the sql server create two temparary tables
called "magic tables".The magic table are called INSERTED and DELETED.These are logical tables and are similar in structure
to to the table on which trigger is fired


        (or)


A trigger is a special kind of a store procedure that executes in response to certain action on the table like
insertion, deletion or updation of data. It is a database object which is bound to a table and is executed automatically.
You can’t explicitly invoke triggers. The only way to do this is by performing the required action no the table that they
 are assigned to.

Depending on the way the triggers are fired ,they can be further categorized as

1.AFTER trigger.
2.INSTEAD OF triggers.

1.AFTER Trigger:

-->The after trigger can be created on any table for insert ,update or delete operation
-->The after Trigger is fired after the execution of DML operation.
-->AFTER trigger is executed when all the constraints and triggers defined on the table are succssfully executed.

2.INSTEAD OF TRIGGERS:
----------------------
These can be used as an interceptor for anything that anyonr tried to do on our table or view.
If you define an Instead Of trigger on a table for the Delete operation, they try to delete rows, and they will not
actually get deleted (unless you issue another delete instruction from within the trigger)
INSTEAD OF TRIGGERS can be classified further into three types as:-

(a) INSTEAD OF INSERT Trigger.
(b) INSTEAD OF UPDATE Trigger.
(c) INSTEAD OF DELETE Trigger.



DELETING THE TRIGGER:
---------------------
DROP TRIGGER TRIG_NAME

DISABLING A TRIGGER:
--------------------

DISABLE TRIGGER TRIGGER_NAME
ON TABLENAME|DATABASE




for more info:
CLICK HERE

transaction


TRANSACTION:

 A transaction can be defined as a sequence of operations performed together as single logical unit of work.
a single unit of work must possess the following properties called ACID(Atomicity,Consistency,Isolation,Durability)


1.Atomicity:
------------
  this states that either all the data modifications are performed or none of them are performed.

2.Consistency:
--------------
this states that all the data is in a consistent state after the all the transaction is completed successfully

3.ISOLATION:
------------
This  states that any data modification made by concurrent transactions must be isolated from modifications made by other

 concurent transactions.


4.DURABILITY:
-------------
This states that any change in data by a completed transaction remains permanently in effect in the system.
therefore ,any change in the data due to a completed transaction persists even in the event of the system failure








Transactions:
------------
Transactions group a set of tasks into a single execution unit. Each transaction begins with a specific task and ends when all the tasks in the group successfully
complete. If any of the tasks fails, the transaction fails. Therefore, a transaction has only two results: success or failure. Incomplete steps result in the
failure of the transaction.

Users can group two or more Transact-SQL statements into a single transaction using the following statements:

1.Begin Transaction
2.Rollback Transaction
3.Commit Transaction
4.Save transaction

If anything goes wrong with any of the grouped statements, all changes need to be aborted.
The process of reversing changes is called rollback in SQL Server terminology.
If everything is in order with all statements within a single transaction, all changes are recorded together in the database.
In SQL Server terminology, we say that these changes are committed to the database.

1.Begin Transaction:
--------------------
Is used to set the starting point of transaction.

2.Rollback Transaction
----------------------
is used to undo the changes

3.Commit Transaction
--------------------
is used to save the changes

4.4.Save transaction
--------------------

IS USED to establish save points that allow partial rollback of a transaction.






indexes


Index is a database object, which can be created on one or more columns . When creating the index will read the column(s)
and forms a relevant data structure to minimize the number of data comparisons. The index will improve the performance of data retrieval and adds some
overhead on data modification such as create, delete and modify.
So it depends on how much data retrieval can be performed on table versus how much of DML (Insert, Delete and Update) operations.


indexes are two types
1.clustered index
2.Nonclustered index.

1.clustered index:
------------------


-->A clustered index  is an index that srortes the data rows in the table based on their key values.

-->onley one clustered index can be created per table


in the clustered index ,data is stored at the leaf level of the B-tree.


sql server performs the following steps when it uses a clustered index to search for a value

1.SQL server obtains the address of the root page from the sysindexes table,which is a system table containing the details of all the indexes in the database


2.the serch value is compared with the key values on the root page .

3.the page with the highest key values less then or equal to serch value is found

4.the page pointer is followed to  the next lower level in the index .

5. steps 3 and 4 are repeated until the page is reached .

6.the rows of the data are searched on the datapage untill the serch value is found .if the serch value is not found on the data page ,no rows are returned by
the query


2.Nonclustered index.
----------------------
Similar to the clustered index,a Nonclustered index also contains the index key values and the row locators that point to the
storage location of the data in the table .however ,in a nonclustered index,the physical order of the rows is not the same as the
index order .



non clustered indexes are created on columns used in joins and where clause .
the sql server creates non clustered indexes by default when the CREATE  INDEX command is given .
there can be as maney as 999 nonclustered indexes per table.


the data in a non clustered index is present in a random order ,but the logical ordering is specified by the index

EX:


CREATE DATABASE VENKAT


USE VENKAT
GO

---CREATE TABLE


CREATE TABLE Student
(
          StudId smallint,
StudName varchar(50),
Class tinyint
)

 -----TABLE 2-----
CREATE TABLE TotalMarks
(
StudentId smallint,
TotalMarks smallint
);


 -----creating the indexes----

CREATE CLUSTERED INDEX CL_IX_Student
ON Student(StudId)
WITH FILLFACTOR = 10

 ---DROP INDEX----


DROP INDEX CL_IX_Student ON Student


---INSERTING THE VALUES ----


INSERT INTO Student
(
StudId ,
   StudName ,
   Class
   )
   VALUES(1,'SRI',2),
(2,'MOHAN',3),
(3,'MANU',2),
(4,'HARI',4),
(5,'KRISHNA',3),
(6,'MANU',3),
(7,'KIRAN',3),
(8,'VENKAT',4),
(9,'AKHEEL',5),
(10,'RAJENDER',5),
(11,'KISHOR',6),
(12,'KRISHNA',4)

---TO RETRIVE THE ALL THE REC FROM TABLE----

   SELECT * FROM STUDENT
 
 
 









DDL,DML,DCL,TCL


DML:

DML is abbreviation of Data Manipulation Language. It is used to retrieve, store, modify, delete, insert and update data in database.

Examples: SELECT, UPDATE, INSERT statements

statements are used for managing data within schema objects. Some examples:

    SELECT - retrieve data from the a database
    INSERT - insert data into a table
    UPDATE - updates existing data within a table
    DELETE - deletes all records from a table, the space for the records remain
    MERGE - UPSERT operation (insert or update)
    CALL - call a PL/SQL or Java subprogram
    EXPLAIN PLAN - explain access path to data
    LOCK TABLE - control concurrenc


DDL

DDL is abbreviation of Data Definition Language. It is used to create and modify the structure of database objects in database.

Examples: CREATE, ALTER, DROP statements

statements are used to define the database structure or schema. Some examples:

    CREATE - to create objects in the database
    ALTER - alters the structure of the database
    DROP - delete objects from the database
    TRUNCATE - remove all records from a table, including all spaces allocated for the records are removed
    COMMENT - add comments to the data dictionary
    RENAME - rename an obj

DCL

DCL is abbreviation of Data Control Language. It is used to create roles, permissions, and referential integrity as well it is used to control access to database by securing it.

Examples: GRANT, REVOKE statements


TCL

TCL is abbreviation of Transactional Control Language. It is used to manage different transactions occurring within a database.

Examples: COMMIT, ROLLBACK statements

ROLLBACK is used for revoking the transactions until last commit.
COMMIT is used for commiting the transactions to the database.
Once we commit we cannot rollback. Once we rollback we cannot commit.
Commit and Rollback are generally used to commit or revoke the transactions that are with regard to DML commands.

-------------------------------------------------------------------------------------------------------------

ex:


--CREATING THE DATABASE

CREATE DATABASE SRIRAMA

--USHING THE DATABASE

USE SRIRAMA
GO

----CREATING THE TABLE


IF NOT EXISTS(SELECT * FROM SYS.OBJECTS WHERE name = 'BRANCH' AND [type] = 'U')
BEGIN
CREATE TABLE BRANCH
(
BRANCH_ID INT ,

BRANCH_NAME VARCHAR(20)

)
END


-----ADD THE NEW COLUMN TO THE BRANCH TABLE 

ALTER TABLE BRANCH ADD LOCATION VARCHAR(30)

---increase the size of the column 

ALTER TABLE BRANCH ALTER COLUMN LOCATION  VARCHAR(50)

---drop the column 
ALTER TABLE BRANCH DROP COLUMN LOCATION


----insert the records into the branch 
INSERT INTO BRANCH VALUES (1,'CSE') ----method 1

INSERT INTO BRANCH VALUES (2,'IT'),
                                                         (3,'ece') -----method 2

-----delete
DELETE FROM BRANCH WHERE ID=3 ---onley the id=3 record will be deleted 
DELETE FROM BRANCH   ---all the records will be deleted from branch table 


----insert the records into the branch 
INSERT INTO BRANCH VALUES (1,'CSE') 


INSERT INTO BRANCH VALUES (2,'IT'),
                                                         (3,'ece') -----method 2

---update the record in the branch table 
UPDATE BRANCH SET  BRANCH_NAME='IT' WHERE BRANCH_ID=1    ------ onley one record       
                                                                                                             is updated whose id=1
UPDATE BRANCH SET  BRANCH_NAME='ECE' --all records updated branchname as ECE





                                                     
----DROP THE TABLE 
DROP TABLE BRACH 

--Truncate 
TRUNCATE TABLE BRANCH 


THANKS,
venkat......


SQL CONSTRAINTS


CONSTRAINTS:

>Constraints are used to limit the type of data that can go into a table.
>constraints  are used apply business rules for the database tables

the constraints available in sql are
1. primary key  constraint
2. Foreign key   constraint
3. not null  constraint
4. unique key  constraint
5 .check constraint
6. default constraint


1.PRIMARY KEY:
                   it defines a column or combination of columns which uniquely identifies each row in the table


syntax: column_name datatype [constraint constraint_name] PRIMARY KEY

EX:




IF NOT EXISTS(SELECT * FROM SYS.OBJECTS WHERE name = 'BRANCH' AND [type] = 'U')
BEGIN
CREATE TABLE BRANCH
(
BRANCH_ID INT
CONSTRAINT PK_BRANCH_BRANCH_ID PRIMARY KEY ,
BRANCH_NAME VARCHAR(20)

)
END


Here primary key is applied to Branch_id column.

insert the records to the BRANCH table 

INSERT INTO BRANCH VALUES (1,'CSE')

INSERT INTO BRANCH VALUES (1,'IT') --ERROR Bcz Primary key violation duplicate values are not allowe









2.FOREIGN KEY:


This key refers some other columns and accepts only the values which available in it's parent key but allows
null values and duplicate values


EX:
TABLE1:

IF NOT EXISTS(SELECT * FROM SYS.OBJECTS WHERE name = 'BRANCH' AND [type] = 'U')
BEGIN
CREATE TABLE BRANCH
(
BRANCH_ID INT 
CONSTRAINT PK_BRANCH_BRANCH_ID PRIMARY KEY ,
BRANCH_NAME VARCHAR(20)

)
END

----insert the record 
INSERT INTO BRANCH VALUES (1,'CSE')
INSERT INTO BRANCH VALUES (2,'IT')

TABLE2:


CREATE TABLE FACULTY
       (
F_ID INT IDENTITY(100,1)
CONSTRAINT PK_FACULTY_F_ID PRIMARY KEY,
NAME VARCHAR(30) NOT NULL,
BRANCH_ID INT
        CONSTRAINT FK_FACULTY  FOREIGN KEY REFERENCES BRANCH(ID)
        )

--insert the records into faculty table

INSERT INTO FACULTY VALUES ('HARISH',1)  --INSERTED BCZ BRANCH_ID RECORD EXIST
                                                                                    IN BRANCH TABLE

INSERT INTO FACULTY VALUES ('ashok',40) ---error bcz foreign key violation id 40 is not exist in 
                                                                                   branch table





3.NOT NULL  CONSTRAINT:

                       doesn't allow the null values but allows the duplicates

ex: CREATE TABLE  MYTB
(
             ID INT(5),
             NAME VARCHAR(20)
                    CONSTRAINT NM_NN NOT NULL
)

insert records into mytb

INSERT INTO MYTB VALUES (1,'VENKAT') --INSERTED 
INSERT INTO MYTB(ID) VALUES (2)--error bcz not null 


4. UNIQUE KEY:
                   Doesn't allow the duplicates but allow the one   null value




ex:
 CREATE TABLE DEPT
(
DEPTNO TINYINT
                    CONSTRAINT PK_DEPTNO PRIMARY KEY,
DEPTNAME VARCHAR(10) NOT NULL,
DEPTLOCATION VARCHAR(10)
                        CONSTRAINT dp_loc_uk UNIQUE
)

insert the records

insert into dept (1,'cse','hyd')--inserted
insert into dept(2,'it',hyd)--error bcz unique key violation 




5.check constraint:    allows to create a domain using 'in' or 'between' and 'and' links to column to allow only those
set of values.



CREATE TABLE FACULTYINFO
(
EMP_ID SMALLINT CONSTRAINT PKEMPID PRIMARY KEY,
EMPNAME VARCHAR(20) NOT NULL,
EMP_ADDRESS VARCHAR(55)
              CONSTRAINT ADDDEFAULT DEFAULT 'HYD',
MOBILE VARCHAR(10),
EMAILID VARCHAR(10),
GENDER VARCHAR(1) CONSTRAINT CHKGENDER_ck CHECK (GENDER IN ('M','F')))

Here the check constraint is applied to Gender column values 'M','F' is allowed only



6.DEFAULT constraint:


                to set the default value for a column insted of taking as null.


    ex:CREATE TABLE FACULTYINFO
(
EMP_ID SMALLINT
                  CONSTRAINT PKEMPID PRIMARY KEY,
EMPNAME VARCHAR(20) NOT NULL,
EMP_ADDRESS VARCHAR(55)
                     CONSTRAINT ADDDEFAULT DEFAULT 'HYD',
MOBILE VARCHAR(10),
EMAILID VARCHAR(10),
GENDER VARCHAR(1)
                 CONSTRAINT CHKGENDER CHECK (GENDER IN ('M','F'))
)







OOPS- C#


OOPS:
----
OOP is a design philosophy. It stands for Object Oriented Programming.
Object-Oriented Programming (OOP) uses a different set of programming languages
than old procedural programming languages (C, Pascal, etc.).
 Everything in OOP is grouped as self sustainable "objects".
  Hence, you gain re-usability by means of four main object-oriented programming concepts.


The main use of the oops is sharing and security is possible in oops concepts.

the main things in the oops are class and object

OBJECT:
-------

An object can be considered a "thing" that can perform a set of related activities.
The set of activities that the object performs defines the object's behavior.

For example, the hand can grip something or a Student (object) can give the name or address.

In pure OOP terms "an object is an instance of a class. "

CLASS:
------
Class is a blue print .
the class compressed  of the member data(class level variables) member function

in the class creation time no memorey is allocated for the class member variables
onley the object creation time the memorey is allocated for the variable.


The features of the oops are:
1.abstraction
2.encapuslation
3.inhiritence
4.polymorphism


1.Abstraction:
-------------
Abstraction is another good feature of OOPS.
Abstraction means to show only the necessary details to the client
of the object.

ex:Do you know the inner details of the Monitor of your PC? What happen when you switch ON Monitor?
Does this matter to you what is happening inside the Monitor?
No Right, Important thing for you is weather Monitor is ON or NOT.


 When you change the gear of your vehicle are you really concern about the inner details of your vehicle engine?
No but what matter to you is that Gear must get changed that’s it!! This is abstraction;
 show only the details which matter to the user.

def2:
-----

Abstraction" simply means showing only those details to the user which are of use to them ,
 and hiding up the unnecessary


demo:public class Mammal

{

         public  string m_color; // Abstract Charactersistic 1

         public string m_height; // Abstract Charactersistic 2

        public string m_weight; // Abstract Charactersistic 1

         public Mammal()

         {

         }

         public void Move()

        {

            // Abstract behaviour

        }

}

// Elephant is a Mammal hence it extends abstract class Mammal

public class Elephant : Mammal

{

         public  string m_color = "gray"; // Gray color

         public int m_height = 120; // 10 feet or 120 inches

        public int m_weight = 1500; // 1500 pounds

         public Elephant()

         {

         }

         public void Move()

        {

            // Implement the Elephant Walks Behaviour

        }

}

 // A whale is also a mammal hence it extends the Mammal class

public class Whale: Mammal

{

         public  string m_color = "darkgray"; // Dark Gray color

         public int m_height = 60; // 5 feet or 60 inches

        public int m_weight = 2000; // 2000 pounds

         public Whale()

         {

         }

         public void Move()

        {

            // Implement the way a Whale swims

         }

}






2.encapuslation:
----------------
Encapsulation is the procedure of covering up of data and functions into a single unit (called class).
An encapsulated object is often called an abstract data type.

NEED FOR ENCAPSULATION:
----------------------

The need of encapsulation is to protect or prevent the code (data) from accidental
corruption due to the silly little errors that we are all prone to make.
In Object oriented programming data is treated as a critical element in the program development
and data is packed closely to the functions that operate on it and protects it from accidental modification
from outside functions.

implementing encapsulation by ushing the acess specifiers:
----------------------------------------------------------

an acess specifier defines the scope of a class member.

TYPES OF ACCESS SPECIFIERS:
---------------------------
C# supports the following acess specifiers:
-->public
-->private
-->protected
-->internel
-->protected internel

1.THE PUBLIC ACESS SPECIFIER:
-----------------------------
the public acess specifier allows a class to share its member variables and member functions with other classes(within or outside
the application).Any member that is declared public can be accessed from outside the class.

ex:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace public_acess_specifier_demo1
{
    class car
    {
        private string carcolor;  //since the variable is private ,it
        //cannot be accessed outside the class defination.

        class bike
        {
            public string bikecolor;//since the variable is public ,
            //it can be acessed outside the class defination
        }
        class program
        {
            public static void Main(string[] args)
            {
                car obj1 = new car();
                bike obj2 = new bike();
                //obj1.carcolor = "red";//error bcz we can not acess private members
                obj2.bikecolor = "yellow";// not error bcz we can acess anyware in the application becoz this is
                //public variable

            }
        }
    }
}




THE PRIVATE ACESS SPECIFIER:
---------------------------

the private acess specifier allows a class to hide its member variables and member functions from other class
object and functions

therefore the private members of a class are not visible outside the class.


ex:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace private_acess_specifier
{
    class car
    {
        private string model;
        void hunk()
        {
            Console.WriteLine("hi this is hunk");
        }
        public void setModel()
        {
            Console.WriteLine("enter the model name:");
            model = Console.ReadLine();

        }
        public void displayModel()
        {
            Console.WriteLine("the model is :");
        }
    }
    class abc
    {
        static void Main(string[] args)
        {
            car obj1 = new car();
            obj1.setModel(); //accepts the model name
            obj1.displayModel(); //display the model name
              //  obj1.honk();//error becoz this is private variable
           // Console.WriteLine(obj1.model);//error becoz private variable
            Console.ReadLine();
        }
    }
}




PROTECTED ACESS SPECIFIER:
--------------------------
the protected acess specifier allows a class to hide its member variables and
member functions from other class objects and functions except the child class.

this concept is importent while implementing the concept of inheritance


ex:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace protected_access_specifier_demo
{
    class car
    {
        protected string model;
        void honk()
        {
            Console.WriteLine("hi i am honk ");
        }
        public void setmodel()
        {
            Console.WriteLine(" enter the model name:");
            model = Console.ReadLine();


        }
        public void displaymodel()
        {
            Console.WriteLine("the model is:");
        }
    }
    class abc
    {
        static void Main(string[] args)
        {
            car abc = new car();
            abc.setmodel();//accepts the model name
            abc.displaymodel();//displays the model name
           // abc.honk();//error bcz honk is private access specifier
            //Console.WriteLine(abc.model);//error becoz it is a protected access specifier

        }
    }
 
}



INTERNAL ACCESS SPECIFIER:
--------------------------


THE internal access specifier allows a class to expose its member variables and member functions to other
class functions and objects with in the application onley


the default access specifier for a class is internal


ex:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace internal_access_specifier_demo
{
    class car
    {
        private string carcolor;
        internal void honk()
        {
            Console.WriteLine("hi i am honk ");
        }
    }

    class bike
    {
        internal string bikecolor;//it is internal
        //it can be accessed outside the class defination
    }

    class abc
    {

        public static void Main(string[] args)
        {
            bike obj1 = new bike();
            car obj2 = new car();
            //obj2.carcolor = "red";// error can not acess private members
            obj1.bikecolor = "blue";
            obj2.honk();//display the message

        }


    }


}









protected internal acess specifier:
-----------------------------------

the protected internal access specifier allows a class to expose its member variables and
member functions to the containing classes or class with in the same application
in addition ,it allows to access to the  derived class outside the application
ex:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace protected_internal_demo
{
    class car
    {
        protected internal string model;
        void honk()
        {
            Console.WriteLine("hi helloooo");

        }
        public void setmodel()
        {
            Console.WriteLine(" enter the model name:");
            model = Console.ReadLine();
        }
        public void displaymodel()
        {
            Console.WriteLine("the model is : ");

        }
        class display
        {
            static int Main(string[] args)
            {
                car abc = new car();
                abc.setmodel();
                abc.displaymodel();
                abc.honk();
                Console.WriteLine(abc.model);
                return 0;

            }
        }

    }

}






3.INHERITANCE:
--------------
-->it is the prime feature of the oops .
-->the process of creating the new classes from already existing class.
-->in the inheritance process existing class is known as the parent/base class,
neweley created class is known as derived class /child class.
-->main purpose of the inheritance is  code re-usability and providing the
additional functionality

types of inheritance:
--------------------
-->single inheritance
-->multiple inheritance.
-->multilevel inheritance.
-->hybrid inheritance
-->hyerarcial inheritance

single inheritance:
-------------------
 Creating a single new class from single base class is known as single inheritance

ex:    [A]
^
|
|
       [B]

Multiple Inheritance:
---------------------
creating the new class from two or more base classes is known as multiple inheritance

ex:    [a]     [b]
^       ^
|_______|
              |
             [c]

multilevel inheritance:
------------------------
creating a new class from already derived class is known as  multilevel inheritance

ex:
      [a]
       ^
       |
       |
      [b]
       ^
       |
       |
      [c]

hyerarcial inheritance:   this is the combination of both multiple and multilevel inheritance
------------------------


ex:   [a]           [b]
^                       ^
|                        |
|____________|
              |
             [c]
              ^
              |
             [d]



polymorphism:
------------
the term polymorphisam was derived from greek words 'poly'means 'maney' and 'morphos' means
'forms'.
polymorphism is the ability to allow a function to exist in different forms.

the polymorphism have two types :
1.static polymorphism
2.Dynamic polymorphism



1.static polymorphism:
---------------------

in static  polymorphism the response to a function is decided at "compile time"


c# uses following approaches to implement static polymorphisam these are


->function overloading for implementing static polymorphism
-->operator overloading for implementing static polymorphism

function overloading:
--------------------


function overloading allows you to use same name for two or more functions.each of these functions having the same name
 must use different function signature.
the signature function is defined by

void addnum(int)
void addnum(int,float)
void addnum(float,float)

the above code the three functions are different because their number and type of  parameters is different


ex:


using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;



namespace fun_and_constructor_overloading_demo

{

    class arithematic

    {

        int a, b, result;

         static int c;

        static  arithematic()//static constructor

        {

            c = 20;

            Console.WriteLine("static constructor invoked");

        }

         public arithematic()

         {

             a = 10;

             b = 3;

             Console.WriteLine("default constructor invoked");

         }

        public arithematic(int p, int q)

        {

            a = p;

           b = q;

            Console.WriteLine("2parametarised constructor invoked");

        }

        public arithematic(int p)

        {

            a = p;

            b = 0;

            Console.WriteLine("1 parametarised constructor invoked");

        }

        public arithematic(int a, int b, int c)

        {

          this.a = a;

          arithematic.c=c;



          this.b = b;

         



            Console.WriteLine("3 param constructor invoked");

        }

        public void add()

        {

            int result=a+b+c;

            Console.WriteLine("sum is :{0}",result);



        }

static void Main(string[] args)

        {

            arithematic obj = new arithematic();//static ,default

            obj.add();

       

    arithematic obj1=new arithematic(3);//1 param

    obj1.add();



 arithematic obj2 = new arithematic(2, 1);//2 params const



 obj2.add();

 arithematic obj3 = new arithematic(2, 1,8);

 obj3.add();

 Console.ReadLine();





}









}

 

}

operator overloading:
---------------------
The concept of overloading a function can also be applied to operators .operator overloading
provides additional capabilities to c# operators when they are applied to userdefined data types.

ex:


using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;



namespace operator_overloding

{

    class  test

    {

        int a, b;

        public test()

        {

        }

        public test(int p, int q)

        {

            a = p;

            b = q;

        }

        public void display()

        {

            Console.WriteLine("a value {0}\t b value{1}", a, b);

        }

        public static test operator +(test x, test y)

        {

            test temp = new test();//hi

            temp.a = x.a + y.a;

            temp.b = x.b + y.b;

            return temp;

        }

        public static test operator -(test x,test y)

        {

            test temp = new test();//hi

            temp.a =x.a-y.a;

            temp.b=x.b-y.b;

            return temp;

        }

        public static test operator *(test x, test y)

        {

            test temp = new test();

            temp.a = x.a * y.a;

            temp.b = x.b * y.b;

            return temp;

        }

        public static test operator /(test x, test y)

        {

            test temp = new test();

            temp.a = x.a/y.a;

            temp.b = x.b/y.b;

            return temp;

        }

   

         public static test operator++(test x)

  {

            x.a++;

            x.b++;

            return x;



        }



           public static test operator --(test x)

           {

               x.a--;

               x.b--;

               return x;

           }

}

class prog



{

        static void Main(string[] args)

        {

            test t1 = new test(4, 6);

            test t2=new test (2,3);

            test t3,t4,t5,t6,t7,t8,t9,t10;

            t3=t1+t2;

            t4 =t1-t2;

            t5 = t1 * t2;

            t6 = t1 / t2;

            t1.display();

            t2.display();

            t3.display();

            t4.display();

            t5.display();

            t6.display();

            t7 = ++t1;

            t8 = t1++;

            t1.display();

            t8.display();

            t9 = --t2;

            t2.display();

            t10 = t2--;

            t2.display();

            t10.display();

            Console.ReadLine();

        }

    }

}















2.Dynamic polymorphism:
-----------------------
in dynamic polymorphism the response to the function is decided at "runtime".



c# uses following approaches to implement static polymorphisam these are:

1.Abstract classes for implementing Dynamic polymorphism.
2.virtual functions  for implementing Dynamic polymorphism.

Abstract classes:
------------------

a class which contains one or more "abstract functions" is known as an abstract class

--> to make any class as abstract use "abstract" keyword.
-->an abstract class can't be instantitated directley.
-->it is compulsory to create /derive a new class from an abstract class in order to provide functionality to its
 abstract functions
-->an abstract class can contain non abstract functions.
-->an abstract class can contain all members of a class
-->by default abstract class functions are not treated as public and abstract.



abstract function:
-------------------
-->a function which contains onley declaration /signature and doesn't contain implementation/body/defination
is known as ABSTRACT FUNCTION
-->To make any function as abstract use 'abstract' keyword
-->an abstract function should be terminated .
-->Overriding of an abstract function is compulsory.

VIRTUAL FUNCTIONS:
------------------
WE are providing new functionality for the base class functions in derived class and base class functions are not usefull
now so base class functions are known as VIRTUAL FUNCTIONS and derived class are known as overriding functions.

-->to make any function as VIRTUAL keyword.
-->to override any virtual function in derived class use override keyword.
-->virtual functions may or mayn't override.



     THE  VIRTUAL FUNCTIONS and Abstract classes will create the bridge from parent to child

simple example for VIRTUAL FUNCTIONS and Abstract classes
     


         parent class                       :           child class
        ---------------------                         --------------------
       
      wish()                                     wish()
    add()                                      mul()
    sub()                                   divide()
       msg()

   
      object creation for the parent and child classes for functions





      case 1:  parent obj1=new parent();
obj1.wish()  ;
 obj1.add()  ;                                  
                 obj1.sub()  ;                              
                          obj1.msg()  ;


      case 2:    parent obj2=new child();
     obj2.wish();


   
   
      case3:      child obj3=new child();
        obj3.wish() ;
 obj3.add() ;                                  
                 obj3.sub() ;                              
                          obj3.msg() ;
 obj3.mul() ;
 obj3.divide();



demo :


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace abstract_virtuval
{
    abstract class parent
    {
        public virtual void display()
        {
            Console.WriteLine("display from parent");

        }
        public void wish()
        {
            Console.WriteLine("wish from parent");
        }
        public abstract void sub();
            public void add()
        {
                Console.WriteLine(" add from parent");

        }
            public void mul()
            {
                Console.WriteLine("mul from parent");
            }
            public void msg()
            {
                Console.WriteLine("hi hello i am from parent");
            }

    }
    class child : parent
    {
        public override void display()
        {
            Console.WriteLine("display from child ");
        }
        public override void sub()
        {
            Console.WriteLine(" sub from child");
        }
        public void div()
        {
            Console.WriteLine(" div from child");
        }
    }
    class program
    {
        static void Main()
        {
            child obj3 = new child();
            obj3.wish();
            obj3.add();
            obj3.sub();
           obj3.mul();
           obj3.msg();
            obj3.div();
            Console.ReadLine();

        }
    }
}
 


NOTE:
Parent class can hold the child class memorey(but not vice versa)
-->when the function is present in the parent class and virtuval state in parent
then it goes to child function and executes
overriding:
----------
when a parent class function is redefined from the child class with the same
function signature

abstract:
--------
any function without body name as abstract









constructor:

-----------

a constructor is a special member function.

-->a constructor is a member method of a class which is invoked automaticalley when an object to the class is created

-->constructor name should be the same as the class name.

-->constructor doesn't have any return type even void also .

two types of constructors are supported by the c#

1.instance constructor

2.static constructor



instance constructor:

--------------------

an instance constructor is called whenever an instance if a class is created .these constructors are used to initilize

the member variables of the class .



static constructor:

------------------

static constructors are used to initilize the static variables of the class.these variables are created by

using the "static "keyword and they store values that can be shared by all the instance of a class





using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;



namespace op2

{

    class calculate

    {

        static int number1;

        public void display(int number)

        {

            Console.WriteLine(number);

        }

        calculate()

        {

            number1++;

            display(number1);

        }

        static calculate()

        {

            number1 = 10;

            number1++;

        }

        static void Main(string[] args)

        {

            calculate cal1=new calculate();

            Console.ReadLine();

        }

    }

}









parameterized constructor:

--------------------------

-->a parameterized constructor accepts arguments to store the values in to the data fields.

-->using the parameterized constructor we can store different set of values into different objects

created to the class





DESTRUCTOR:

-----------

?Destructors? are used to destruct instances of classes. When we are using destructors in C#, we have to keep in mind the following things:



A class can only have one destructor.

Destructors cannot be inherited or overloaded.

Destructors cannot be called. They are invoked automatically.

A destructor does not take modifiers or have parameters.



garbage collector:

-------------------

a garbage collector is a process that automaticalley frees the memorey of object that are no more in use.the decision to involve the destructor is made by

a componentt of the CLR known as the garbage collector.





ex:



using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;



namespace Constructordemo

{

    class test

    {

        int a, b;

        static int c;

        static test()

        {

            c = 34;

            Console.WriteLine("static constructor invoked");

        }

        public test() //instance default constructor

        {

            a = 30;

            b = 12;

            Console.WriteLine("default constructor invoked");

        }

        public test(int p, int q)// instance parametariged

        {

            a = p;

            b = q;

            Console.WriteLine("2param constructor invoked");

        }

        public test(int p)

        {

            a = p;



            Console.WriteLine("1 param constructor invoked");

        }

        public void display()

        {

            Console.WriteLine("{0}\n{1}\n{2}",a,b,c);

        }





        ~test()//destructor

        {

            Console.WriteLine(" i am in the process of destroying the obj");

        }





        static void Main(string[] args)

        {

            test obj=new test();//static instance default

            obj.display();

            test obj2=new test();

            obj2.display();

            test obj3=new test(10,4);

            obj3.display();

            test obj4=new test(67);// instance param const

            obj4.display();

            Console.ReadLine();

        }

    }



     

}

-----------------------------------------------------------THE --END------------------------------------