Beruflich Dokumente
Kultur Dokumente
DATABASE:
TABLES:
Describes how table are used to store rows of data and defined the relationship
between multiple tables.
* In 1989 the American national standards institute (ANSI) published the first set of
standards for
* A database query language called ansi- .sql
Types Of Commands:
1. DDL Commands:
DDL STATEMENTS
* Create Database, Create Table, Create Index, Create Procedure, Create View
* Alter Table, Alter Index, Alter Trigger, Alter Procedure, Alter View.
* Drop Database, Drop Table, Drop Trigger, Drop View, Drop Procedure.
To Create a Database
It creates a new database and the files used to store the database this
statements allocates space to two files .the first file .mdf, will hold the data for the
database .the second file .ldf will hold a record of any changes made to the database.
Syntax:
Create database databasename
Example:
Create database anbu
Syntax:
Use databasename
Example:
Use anbu
Syntax:
Create table tablename (field1 datatype, field2 datatype, field3 datatype,… field n
datatype)
Example:
Create table emp (eno int, ename varchar (20), salary int)
Syntax:
Insert into tablename values (value1, value2, value3,.............value n)
Example:
Insert into emp values (1,'a', 2000)
Insert into emp values (2,'b', 3000)
Insert into emp values (3,'c', 4000)
Insert into emp values (4,'d', 5000)
Insert into emp (eno, ename) values (5,'e')
Example:
Select * from emp
Alter Table
Syntax:
Alter table tablename add/drop fieldname datatype
Example:
Alter table emp add age int
Alter table emp drop age
Drop Table
Syntax:
Drop table tablename
Example:
Drop table emp
Truncate Table
Syntax:
Truncate table tablename
Example:
Truncate table emp
Syntax:
Delete from tablename where condition
Example:
Delete from emp where eno=9
Delete from emp
CHAPTER-3
Select Clauses
> WHERE
> DISTINCT
> ORDER BY
> ASC/DESC
> INTO
> TOP
> GROUP BY
> HAVING
> COMPUTE
Operator Description
Equal
=
Not Equal
<>
> Greater Than
Less Than
<
Greater Than Or Equal
>=
<= Less Than Or Equal
Not Greater Than
!>
Not Less Than
<!
Example:
Select * from emp where salary=4000
Select * from emp where salary<=4000
Select * from emp where salary>=4000
Select * from emp where salary<>4000
Select * from emp where salary!>4000
Select * from emp where salary! <4000
Example:
Select * from emp where salary is null
Select * from emp where salary is not null
Using Like
% Matches any string of zero or more characters
_(UNDERSCORE) Matches any single characters
[] Matches a single character listed within the brackets
[-] Matches a single character within the given range
[^] Matches a single character not listed after the caret
Example:
Select * from emp where empname like 'a%'
Select * from emp where empname like 'bal_'
Select * from emp where empname like ' a [nrg] %'
Select * from emp where empname like 'a [b-h] %'
Select * from emp where empname like 'a [^b-h] %'
Example:
Update emp set salary=salary+1000
Update emp set salary=5000 where eno=9
DISTINCT CLAUSE
Example:
Insert into emp values (9,'i', 2000)
Select * from emp
Select distinct salary from emp
ORDER BY CLAUSE
Example:
Select * from emp order by salary asc
Select * from emp order by salary desc
INTO CLAUSE
Example:
Select eno, ename into stu from emp
Select * from stu
TOP CLAUSE
Example:
Select top 5* from emp
Select top 3 percent * from emp
CHAPTER-4
T-SQL Functions
1. Numeric Function
2. String Function
3. Date And Time Function
4. System Function
5. Calculating Function
6. Conversion Function
7. Other Function
Numeric Function
Example:
Select abs (-12)
Select floor (456.89)
Select ceiling (456.89)
Select rand (1)
Select round (12.345678, 3)
Select sign (-43)
Select sign (43)
Select sign (0)
Select sqrt (16)
Select radians (90)
Select degrees (25)
Select pi ()
Select tan (45)
Select cos (45)
Select sin (45)
String Functions
Example:
Select 'siva' +'ram'
Select ascii ('a')
Select char (65)
Select charindex ('a', 'anbu')
Select charindex ('ar', 'anbuarasu')
Select difference ('anbu','anbu')
Select lower ('anbu')
Select upper ('anbu')
Select replicate (' hai', 10)
Select reverse ('hai')
Select space (10) + 'hai' +space (10) + 'to'+ space (10) + 'everyone'
Select substring ('hello world', 1, 5)
Select stuff ('sevakasi', 1, 4,'ten')
Select soundex ('gita')
Select soundex ('geetha')
Select ' hai'
Select ltrim (' hai')
Select 'hello '+'world'
Select rtrim ('hello ') +'world'
Date Functions:
Datepart Values:
Example:
Select getdate ()
Dateadd ()
-Adds The Number to the Datepart of Date
Syntax:
Dateadd (datepart,number,date)
Example:
Select dateadd (yy, 2, getdate())
Select dateadd (mm, 2, getdate())
Select dateadd (dd, 2, getdate())
Datediff ()
- Returns the number of datepart between the 2 date
Syntax:
Datediff (datepart, date1, date2)
Example:
Select datediff (mm, '2004-1-1', '2005-1-1')
Select datediff (yy, '2004-1-1', '2005-1-1')
Select datediff (dd, '2004-1-1', '2005-1-1')
Datepart ()
Syntax:
Datepart (datepart,date)
Example:
Select datepart (yy, getdate())
Select datepart (dd, getdate())
Select datepart (mm, getdate())
Month ()
-returns the month as integer
Syntax:
Month (date)
Example:
Select month (getdate ())
Year ():
-returns the year as integer
Syntax:
Year (date)
Example:
Select year (getdate())
System functions:
Db_name ()
-returns the current database name
Example:
Select db_name ()
Db_id ()
-returns the database id
Example:
Select db_id ()
Datalength ()
-returns the actual length of an expression
Example:
Select datalength ('anbu')
Host_name ()
-returns the current host computer name
Example:
Select host_name ()
Object_name ()
-returns the database object name
Example:
Select object_name (1)
Object_id ()
-returns the database object id
Example:
Select object_id ('sysobject')
User_name ()
-returns the user name
Example:
Select user_name ()
User_id ()
-returns the user id
Example:
Select user_id ()
Suser_name ()
-returns the server user name
Example:
Select suser_name ()
Suser_id ()
-returns the server user id
Example:
Select suser_id ()
Convertion functions
-It is used to convert an expression from one datatype to another datatype
Syntax:
Convert (datatype, expression)
Example:
Select sname +' mark is '+convert (char, total) from stu1
Other functions
Isnull ()
Returns the specified value in place of null
Isnumeric ()
Returns a value of 1 if expression is in numeric else it will return 0
Isdate ()
Returns a value of 1 if expression is in date format else it will return 0
Group by:
It calculates summary data for groups of rows in a column.
Example:
Select job, max (salary), min (salary) from emp group by job
Having:
It determines which groups are included in the final result.
Example:
Select depno,count (*) a ‘ sno of employes ' from emp group by depno having count(*)>3
Compute:
It produces a single summarized result for each specified group of rows
Example:
Select deptno, empid, ename, salary from emp order by deptno compute sum (salary)
chapter-5
Union operator:
The union operator allows us to combine the result of 2 or more queries into single
result set. A union results in an increase in rows
Create table stu2 (sno2 int, sname2 varchar (20), total2 int)
Insert into stu2 values (1,'abi', 200)
Insert into stu2 values (2,'banu', 300)
Insert into stu2 values (3,'clarin', 400)
Insert into stu2 values (4,'deva', 500)
Insert into stu2 values (5,'ezhil', 600)
Select * from stu2
Create table stu3 (sno3 int, sname3 varchar (20), total3 int)
Insert into stu3 values (1,'abi', 200)
Insert into stu3 values (2,'babu', 300)
Insert into stu3 values (3,'clarin', 400)
Insert into stu3 values (4,'deva', 500)
Insert into stu3 values (5,'kumar', 600)
Select * from stu3
Example:
Select sname2 from stu2
Union
Select sname3 from stu3
Union all:
It is equal to the union command expect that union all selects all values
Example:
Select sname2 from stu2
Union all
Select sname3 from stu3
Joins:
It is used to retrieve and manipulate data from more than one table in a single select
statement. They are four types of joins .they are
1. Restricted joins or cross joins
2. Natural joins
3. Outer joins
4. Self joins
Example:
Create table emp1 (eno int, ename varchar (20), empid int)
Insert into emp1 values (1,'anu', 10)
Insert into emp1 values (2,'babu', 10)
Insert into emp1 values (3,'clarin', 20)
Insert into emp1 (eno, ename) values (4,'deva')
Select * from emp1
Natural joins:
A natural join is one in which the column values being compared are equal for two or
more tables. But join column display only once.
Example:
Select eno, ename, depname from emp1, emp2 where emp1.empid=emp2.depno
Outer joins:
An outer join return all the rows from one table and some rows from another table
They are two types of outer join
1. Left Outer joins
2. Right Outer joins
Example:
Select eno, ename, depname from emp1, emp2 where emp1.empid*=emp2.depno
Example:
Select eno, ename, depname from emp1, emp2 where emp1.empid=*emp2.depno
Self joins:
Joining the table to itself. Joins can also be used within a single table
Example:
Create table emp3 (eno int, ename varchar (20), magno int)
Insert into emp3 values (1,'anu', null)
Insert into emp3 values (2,'babu', 1)
Insert into emp3 values (3,'clarin', 1)
Insert into emp3 values (4,'deva', 2)
Select * from emp3
Select e1.eno, e1.ename, e2.ename from emp3 e1, emp3 e2 where e1.eno=e2.magno
SubQueries:
A sub queries is a select statement nested inside a select, insert, update or delete
statement. A subquery is a nested query.
Example:
Select * from emp where salary in (select salary from emp where ename='d')
Select * from emp where salary not in (select salary from emp where ename='d')
Using Any,All,Some:
Example
Select * from emp where salary> any (select salary from emp where ename='d')
Select * from emp where salary> all (select salary from emp where ename='d')
Select * from emp where salary> some (select salary from emp where ename='d')
Chapter-6
Constraints:
A constrain is a rule defined for a single table taht limits that possible values user
Can enter into the table.they are five types of constraints.
1. Primary key constraint
2. Unique constraint
3. Foreign key constraint
4. Check constraint
5. Default constraint
Syntax:
Create table tablename (fieldname datatype constraint keyname primary key,fieldname
datatype.......)
Example:
Create table emp4 (eno int constraint pk_name primary key, ename varchar (20), salary int)
Insert into emp4 values (1,'anu', 3000)
Insert into emp4 values (1,'babu', 1000)
Example:
alter table emp4 add constraint pk_name primary key (eno)
2. Unique constraint:
It is similar to primary key except it allows null values over one or more column,
But there can be only one row with a null value.
Syntax:
Create table tablename (fieldname datatype constraint keyname unique, fieldname
datatype.......)
Example:
Create table emp5 (eno int constraint uq_name unique, ename varchar (20), salary int)
Insert into emp5 values (1,'anu', 3000)
Insert into emp5 values (1,'babu', 1000)
Insert into emp5 (ename, salary) values ('siva', 2000)
Insert into emp5 (ename, salary) values ('mani', 6000)
Select * from emp5
Example
alter table emp5 add constraint uq_name unique (eno)
Syntax:
Create table tablename (fieldname datatype constraint keyname foreign key references table
name (fieldname), fieldname datatype.......)
Example:
Select * from emp4
Create table emp6 (eno int constraint fo_name foreign key references emp4 (eno), ename
varchar (20), salary int)
Insert into emp6 values (1,'mani', 400)
Insert into emp6 values (2,'anbu', 3000)
Example:
alter table emp6 add constraint fo_name foreign key (eno) references emp4 (eno)
4. Check constraint
It is user defined search condition similar to where clause of select statement.
Syntax:
Create table tablename (fieldname datatype constraint keyname check (expression),
fieldname datatype.......)
Example:
Create table emp7 (eno int, ename varchar (20), salary int constraint ck_name check
(salary<=10000))
Insert into emp7 values (1,'anu', 3000)
Insert into emp7 values (2,'banu', 10000)
Insert into emp7 values (1,'arul', 11000)
5. Default constraint
we can define default constraint for a column to supply a value when a user does not
enter a value. A column can have only one default constraint.
Syntax:
Create table tablename (fieldname datatype constraint keyname default value, fieldname
datatype.......)
Example:
Create table emp8 (eno int, ename varchar (20), salary int constraint df_name default 2000)
Insert into emp8 values (1,'anu', 3000)
Insert into emp8 (eno,ename) values (2,'banu')
Select * from emp8
Example:
alter table emp8 add constraint df_name default 0 for salary
Identity:
The column identity property generates incremental values for the column that identify
Each row inserted into the table. we can use this feature to generates sequential number
1. A table can have only one column with the identity property
2. A column with identity property cannot be updated.
3. A column with identity property does not allow null to be inserted.
4. A column with identity property must have an integer or decimal datatypes.
Syntax:
Identity (seed, increment)
Seed: is the value that is used for the very first row loaded into the table
Example:
Create table stu4 (studid int identity (101, 1), name varchar (10))
We can use system function ident_seed and ident_incr to determine the seed and
incremental values for an identity column.
Syntax:
ident_seed ('tablename')
ident_incr ('tablename')
Example:
Select ident_seed ('stu4')
Select ident_incr ('stu4')
Defaults:
A Default specifies a value to be inserted into a column. A default can be applied to
multiple columns in multiple tables. After a default has been created it has to bind to a
column or user defined datatype.
Syntax:
Create default defaultname as constant _ expression
Example:
Create table stu5 (stid int, name varchar (20), mark int)
Insert into stu5 values (1,'john', 400)
Binding defaults:
Syntax:
exec sp_bindefault default_name, objectname
Example:
Exec sp_bindefault defmrk,'stu5.mark'
Insert into stu5 (stid,name) values (2,'siva')
Select * from stu5
Unbinding defaults:
Syntax:
exec sp_unbindefault objectname
Example:
Exec sp_unbindefault 'stu5.mark'
Dropping defaults:
Syntax:
Drop default defaultname
Example:
Drop default defmrk
Rules:
Rules are used to restrict the range and format to possible values that can enter in a
column.
Syntax:
create rule rulename as condition
Example:
Create rule rulmark as @mark<=500
Binding rules:
Syntax:
Exec sp_bindrule rulename,'objname'
Example:
exec sp_bindrule rulmark,'stu5.mark'
Select * from stu5
Insert into stu5 values (3,'kumar', 400)
Unbinding rules:
Syntax:
Exec sp_unbindrule 'objname'
Example:
exec sp_unbindrule 'stu5.mark'
Drop rule:
Syntax:
Drop rule rulename
Example:
Drop rule rulmark
Chapter-7
Views:
A view is a virtual table whose content are defined by a query. Like a real table a view
consist of set of named columns and rows of data.
Creating views:
Syntax:
Create view view_name
As
Select statement (with check option)
Example:
Create view eview
As select sno, sname from stu1
Manipulating views:
Example:
Insert into eview values (11,'k')
Select * from stu1
Select * from eview
Dropping views:
Syntax:
Drop view view_name
Example:
Drop view eview
Indexes:
An Index is a structure that provides for locating one or more rows directly.
Without an index, sql server has to perform a table scan, which involves searching through
the entire table. Index is a structure associated with a table that speeds retrieval of the rows
in the table.
Types of index
1. Clustered index
2. NoClustered index
1. Clustered index:
It will sort and store the data rows in the table based on their key values.
2. Noclustered index:
The data rows are not stored in order based on the noclustered key.
Creating index:
Syntax:
Create [clustered/nonclustered] index index_name on tablename (column name)
Example:
Create clustered index ind_no on stu1 (sno)
Create nonclustered index ind_no on stu1 (sno)
Dropping indexes:
Syntax:
Drop index table.index
Example:
Drop index stu1.ind_no
Chapter-1
Sql Server Programming.
Transact Sql Statement For Script Processing:
These statements are used within sql scripts to add functionality similar to that
provided by Procedural programming languages.
Syntax:
Declare @variable name datatype, @variable name datatype, ........
Example:
Declare @x int, @y int, @z int
Set statement:
To set or assign a value to a variable
Syntax:
Set @variablename =expression
Example:
Set @x=10
Set @y=20
Example1:
Declare @x int, @y int, @z int
Set @x=10
Set @y=20
Set @z=@x + @y
Print @x
Print @y
Print 'the result of two numbers is '+convert (varchar, @z)
Example2:
Declare @design varchar (20), @empname varchar (15)
Select @empname =ename, @design=job from emp where empno=101
Print 'employee name is '+ @empname
Print 'employee job'+ @design
Variables:
It is used to store data
Types:
1. Local variables
2. Global variables
1. Local variables:
They are often used in batches stored procedure, statements blocks. They are declared in
the body of batch or procedure using the declare statement.
2. Global variables:
They are predefined and maintained by the system. We can refer to them in script
without declaring them. Global variables start with 2 at symbols (@@).
@@version:
Date and number of the current version of sql server
Example:
Select @@version
@@servername:
Name of the server
Example:
Select @@servername
@@language
Name of the current language in use
Example:
Select @@language
@@langid
Local language id of the language in use
Example:
Select @@langid
@@rowcount
Number of rows affected by the last query
Example:
Select @@rowcount
@@trancount
Number of active transactions for the current user
Example:
Select @@trancount
@@error
Error number for the last t-sql statement executed
Example:
Select @@error
@@cursor_rows
Number of qualifying rows in the last opened cursor
Example:
Select @@cursor_rows
@@identity
Returns the last inserted identity value
Example:
Select @@identity
@@fetch_status
Status of the last cursor fetches statement
Example:
Select @@fetch_status
@@connections
No of logins or attempted logins since sql server started
Example:
Select @@connections
Temporary tables:
Temporary tables are used to store table data within a complex script. In addition
they provide a way for us to test queries against temporary data rather than permanent data.
Example:
Select * into #stu6 from emp1
Select * from #stu6
Example:
Create table ##stu7 (sno int, sname varchar (20), salary int)
Insert into ##stu7 values (1,'a', 2000)
Select * from ##stu7
Chapter-2
Conditional processing:
To execute a statement or block of statements based on a condition
1. If.....else
Syntax:
If
{statement/begin.....end}
Else
{statement/begin.....end}
Example:
Declare @duedate datetime
Select @duedate=returndate from stu where stuid=101
If getdate ()>@duedate
Print 'due date over must pay fine'
Example:
Declare @desig varchar (20)
Select @desig=job from emp where empno=101
If @desig='manager'
Update emp set salary=salary+2000 where empno=101
Else if @desig='clerk'
Update emp set salary=salary+1000 where empno=101
Else if @desig='analyst'
Update emp set salary=salary+500 where empno=101
Continue statement:
Example:
Declare @x int
Set @x=0
While @x<=15
Begin
Select @x=@x+1
If @x%2=0
Continue
Print @x
End
Chapter-3
Stored procedure:
A stored procedure is a database object that contains one or more sql statements.
Stored procedure are precompiled that means that the execution plan for the sql
code is compiled the first time the procedure is executed and is then saved in its compiled
form. It execute faster than an equivalent sql script
Syntax:
Create procedure procedurename
{@parameter datatype.........}
As sql statement
Example:
create procedure add_prod
As
Select sno, sname from stu1
Example:
Exec add_prod
Example:
Create procedure ins1
@pid int,
@pname varchar (10),
@price int
As
Insert into stu1 (sno,sname,total) values(@pid,@pname,@price)
Example:
Declare @result int
Execute findpro 25,10,@result output
Print 'the product is '+convert (varchar, @result)
Chapter-4
Triggers:
A trigger is a special type of stored procedure that executes automatically when an
insert, update, or delete statement is executed on a table.
Benefits
1. Triggers provide a powerful way to control how action queries modify the data in our
database
2. Help secure the integrity of data by preventing unauthorized or inconsistent changes to
be made
Creating triggers:
Syntax:
Create trigger triggername
On tablename
For
Delete, insert, update
As
Sql statement
Example:
Create table stu6 (sno int, sname varchar (20), salary int)
Syntax:
drop trigger triggername
Example:
drop trigger forins
Chapter -5
Cursors:
Most of the operations we performed in sql server are set-oriented-the operation
works with an entire set at a time.
A cursor lets us retrieve data from a result set one row at a time-row oriented operation.
We use a cursor to identity the row we want to retrieve from the result set.
Declaring a cursor:
Syntax:
Declare cursorname cursor
For
Select statement
Example:
Declare cur_prod cursor static
For
Select sno, sname from stu1
Opening a cursor:
The open statement opens a cursor. After a cursor has been opened, use the global
variable. @@cursor_rows to determine the number of qualifying rows in the last opened
cursor.
Syntax:
Open cursor_name
Example:
Open cur_prod
Syntax:
Fetch next |prior |first |last |absolute n |relative n | from cursorname
Example:
Fetch next from cur_prod --->retrieves the next record
Fetch prior from cur_prod --->retrieves the previous row
Fetch first from cur_prod --->retrieves the first record in the table
Fetch last from cur_prod --->retrieves the last record in the table
Fetch absolute 2 from cur_prod --->retrieves absolutely the 2nd rows
Fetch relative 3 from cur_prod --->retrieves relative of 3rd record
Closing a cursor:
The close statement releases any memory being used for buffering.
Syntax:
Close cursorname
Example:
Close cur_prod
Removing a cursor:
Syntax:
Deallocate cursorname
Example:
Deallocate cur_prod
Chapter-6
Transaction processing:
Whenever a request to modify the database is received, a copy of both old and new
states of database affected portion in transaction log. These changes are recorded in a
transaction log before they are made to the database itself.
Begin transaction:
Marks the starting point of a transaction.
Commit transaction:
Marks the end of a transaction and makes the changes within the transaction a
permanent part of the database.
Rollback transaction:
Rolls back a transaction to the starting point or to the specified point
Save transaction:
Sets a new save point within a transaction. the save point defines a location to
which a transaction can return if part of transaction is conditionally cancelled.
Example:
Create table stu7 (sno int, sname varchar (20), salary int)
Insert into stu7 values (1,'a', 200)
Insert into stu7 values (1,'a', 200)
Insert into stu7 values (1,'a', 200)
Insert into stu7 values (2,'b', 300)
Insert into stu7 values (3,'c', 400)
Insert into stu7 values (4,'d', 500)
Insert into stu7 values (5,'e', 600)
Select * from stu7
Example.2:
Begin tran
Delete stu7 where sno=1
Save tran e1
Delete stu7 where sno=2
Save tran e2
Select * from stu7
Rollback tran e2
Select * from stu7
Rollback tran e1
Select * from stu7
Chapter-7
Syntax:
Sp_helpdb databasename
Example:
Sp_helpdb anbu
Syntax:
Sp_help objectname
Example:
Sp_help stu1
Syntax:
Sp_helptrigger tablename
Example:
Sp_helptrigger stu6
Syntax:
Sp_helptext objectname
Example:
Sp_helptext forins
Syntax:
Sp_helpuser username
Example:
Exec sp_helpuser
Syntax:
Sp_helpconstraint tablename
Example:
Sp_helpconstraint emp4
Sp_helpconstraint emp5
Sp_helpconstraint emp6
Sp_helpconstraint emp7
Syntax:
Sp_helpindex tablename
Example:
Sp_helpindex stu1
Example:
Exec sp_tables
9. To change the name of a database object (table, column, view, trigger, stored procedure,
database...etc)
In the current database
Syntax:
Sp_rename object name, new name
Example:
Exec sp_rename 'stu','stu1'
Syntax:
Sp_stored_procedures
Example:
Exec sp_stored_procedures
Syntax:
Sp_addtype typename, datatype, null |not null
Example:
Exec sp_addtype birthday, int, 'null'
Syntax:
Sp_droptype typename
Example:
Exec sp_droptype 'birthday'
Example:
Select * from information_schema. tables
Example:
Select * from information_schema.table_constraints
Example:
Select * from information_schema. views
System tables:
The information used by Microsoft sql server and its components are stored in special
tables knows as system tables. System tables should not be altered directly by any user.
1. sysdatabase
2. sysobjects
3. sysconstraints
4. syscolumns
5. sysusers
6. sysindexes
Example:
Select * from sysdatabases
Select * from sysobjects
Select * from sysconstraints
Select * from syscolumns
Select * from sysusers
Select * from sysindexes
=================================================================