Thursday, December 16, 2010

SQL SERVER TUTORIAL 2:::::::::::::::::::HOW TO USE SQL SERVER MAJOR CONCEPTS (FOREIGN KEY ,STORED PROCEDURES,TRANSACTION ETC.,)

Here in this tutorial the advanced conepts of sql server are explained in detailed manner :::
CONTENTS

1. Foreign key references
2. Predefined funcitons in sql
3.Aggregate functions
4. subquery
5.  Functions
6. STORED PROCEDURES
7. INDEXES AND CURSORS
8. CURSORS
9. TRANSACTIONS
10. TRANSACTION STORED PROCEDURE


1. Foreign key references

  • Referential integrity means one table depend on the another table.
  • The foreign key should be assigned to the column of the table where there is primary key for that column is assigned in the another table. Ie., the column should be same
create table items(itemno int primary key,
itemname varchar(13) not null, itemqty int not null,
 itemprice float not null, check (itemprice>0))

create table customers(cusno int primary key,
custname varchar(23),itemno int references items(itemno),qty int)

here referring table is items and referring column is itemno



syntax  2:
create table ac_master(acno int primary key,
name varchar(13) not null, address varchar(14) not null,
 balance float not null)

create table tr_master(acno int,
amt int,constraint fk_acno foreign key(acno)
references ac_master(acno))



To delete the parent records directly without deleting the child records:

On delete cascade



create table tr_master1(acno int,
amt int,constraint fk_acno1 foreign key(acno)
references ac_master(acno)on delete cascade)

Group by having condition

select * from stu group by sno
select * from stu group by sno having sname='jj'


2. Predefined funcitons in sql

Upper(char)
select upper(Accname) from accdetails
lower(char)
select lower(Accname) from accdetails

replace
select accno,accname,creationusername ,
replace('10','aaa','nandu') from accdetails
where accname='aaa'
length


3.Aggregate functions


Sum( ): select sum(sal) from stu
Avg( ):select avg(sal) from emp
Count :select count(sal) from emp
Count(*):select count(*) from sal
Max() : select max(sal) from emp
Min( ): select min(sal) from emp
Abs(): select abs(-10)
Floor():select floor(17.98)
Variance:select variance(sal) from emp
Exp(n):exponential select exp(3)
Mod(min): remainder of division select mod(10,2)
Powe(m,n):select power(10,2)
Round: select round(1234.45454)
Sign(): select sign(15)
Cos()
Tan()
Sin()
Sinh()
Cosh()
Sqrt()


4. subquery


Select * from emp where sal>(select avg(sal) from emp)

select * from flight_details where income=(select max(income)from flight_details where dest=’delhi’)

select * from pilot_master where pno=(select pno from flight_details where income=
(select max(income) from flight_details where dest=’delhi’) and dest=’delhi’)

Select * from stu_info where science>(select avg(science) from stu_info and name like ‘n%’

Select * from stu_info where name=(select name from stu_info where (science+maths+social)>250)



5.  Functions

Two types:
1.system defined :select max(sal)
2.user defined


Return a value


Create function maxoftwo(@n1 int,@n2 int)
Returns int
As
Begin
Declare @big int
if  @n1 > @n2
set @big = @n1
else
set @big = @n2
return @big
end

to run a function:  select master.dbo.maxoftwo(10,20) 


6. STORED PROCEDURES

TWO KINDS
INPUT PARAMETERS—takes values from function/procedure
OUTPUT PARAMETERS—return a value from storedprocedure

Syntax:INSERT
Create procedure sp_student_insert
As
Begin
Insert into student values(2,’nandu’,12,23,34)
End


For execution
Execute sp_student_insert
Or exec sp_student_insert
update

update stu set marks=100 where sno=3
Display:
Create procedure sp_student_display
As
Begin
Select * from student
End

Delete:
Create procedure sp_stu_delete
As
Begin
Delete from stu where sno-90
End

Commands used in stored procedure:


Declare @ abc int
Set @abc=10
Print @abc

1. Input paramets query:



Create procedure sp_student_inputparamets
@sno int,@sname varchar(30),@marks float
As
Begin
Insert into student values(@sno,@sname,@marks)
End

exec sp_students_inputparameters 100,’nan’,56,34


Drop procedure

Drop procedure <procedure name>

Ex., drop procedure sp_stu_input

 2. OUTPUT PARAMETERS

Create procedure sp_stu_count
@count int output
--here must mention output to
--returnn a value from stored procedure
As
Begin
Select @count=count(*) from student
End


To call stored procedure


Declare @count int
Exec sp_stu_count @count=@count output
Print @count









7. INDEXES AND CURSORS

Index is a technique for record searching

We can create only one cluster index for one table

1.clustered—
It is segregated grouping to find records
Only one clustered index for one table

search based on single column
2.nonclustered—search is based on more than one column


Create clustered index index_eno on emp(eno)

Create clustered index index_accno on accdetails(accno)

Create nonclustered index index_accname on accdetails(accname)


For one column both clustered and nonclustered cannot be applied Clustered:
Em-db-table-rightclick-design table-sno right click-index/keys
-new sno-asc-create clustered index
Nonclusterd:
Table-rightclick-sname-rightclick-index/keys-new-sname-don’t tick creat clustered index because it is

Nonclustered index-close
Note:
Within one table clustered and non clustered index will not work
Any one for one table


8. CURSORS

It is a dataset which can hold more data
Setps:
1.           create a cursor
2.           open a cursor
3.           fetch a cursor
4.           close the cursor
5.           deallocate the cursor



syntax:
1.           declare <cursorname> cursor for <selectstatement>
2.           open <cursorname> into <local variable>
3.           0-fetch succeded
4.           1-failed and record missed
5.           2-fetch failed and end of record set
6.           close <cursor name>
7.           deallocate<cursorname>



--local variables created
declare @sno int
declare @ sname varchar(10)
--creation of cursor
declare cursorstudent cursor for
select sno,sname from stu
--open cursor
open cursorstudent
--fetching records
fetch next from cursorstudent into
@sno,@sname
print @sno
print @sname
while @@fetch_status=0
begin
fetch next from cursorstudent int @sno,@sname
print @sno
print @sname
end
--closing cursor

close cursorstudent
--deallocating cursor
deallocate cursorstudent

9. TRANSACTIONS

 Transactions are all about autommicity
i.e.,data consistancy.smallest grouping of statements
steps for transaction:

1.           begin transaction
2.           commit a transaction
3.           rollback a transaction
4.           save a transaction
begin trans <transactionaname>
commi trans <transactionname>
rollback trans <transacionname>
save trans savepointname




create table account(accno int primarykey identity(1,1))
--identity to increment the value
begin tran begintrans
insert into account default value--1
insert into account default value--2
insert into account default value--3
save tran savepointA--4
insert into account default value--5
insert into account default value--6
insert into account default value--7
save tran savepointB--8
insert into account default value--9
insert into account default value--10
insert into account default value--11
---first run above only
rollback tran savepointB--here 6records are opened
--or
rollback tran savepointA--here 3 records are opened
--or
rollback tran begintrans--0 records because no transactions
--or
commit tran begintrans--here 9 records




10. TRANSACTION STORED PROCEDURE

Create table account_details(accountno Int identity(1,1),name varchar(20),accounttype varchar(20),bal float)
Insert into account_details(1,’aaa’,’savings’,1000)
Insert into account_details(2,’aaa’,’savings’,1000)
Select * from accoutn_details
--create procedure






create procedure sp_acc_transfer(@savingsaccno int, @currentaccno int)
as
begin
begin transaction t1
save transaction savepoint
update account_details set bal=bal-30
where accountno=@savingsaccno
if(@@rowcount=0)
rollback transaction savepoint begin
update account_details set bal=bal+90
where accno=@currebt accno
if(@@rowcount=0)
begin
print @@rowcount
rollback transaction savepoint begin
end
else
commit transaction t1
end
exec sp_account_transfer 1,2
select * from account_holder
print @@ rowcounts

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

SQL SERVER 2005 TUTORIAL 1::::::::: INTRODUCTION AND BASIC SYNTAXES

In this tutorial i will explain all the basic concepts with syntax and examples :::::::::::::::::::::::::::
SQL SERVER


  • SQL stands for Structured query language
  • Any dbms based on RDBMS use this sql
  • IBM developed “system-r” as first  DBMS and the actual name is given as “SEQEL”
  • But first commercially  released by ORACLE company
  • ANSI provides standard for SQL
  • SQL used in SQL server is called Transact SQL
  • Sql is a common language for any RDBMS
  • Sql was actually developed by IBM corporation in their project named “System-R”, which is the first RDBMS.
  • Actual name  given by IBM is ‘SEQUEL’ i.e., structured query language
  • But later the name was changed to SQL and was first commercial released by ORACLE corporate

Sql server 2005 features

  1. High availability: fail over clustering and database mirroring technologies
  2. management tools: introduce application programming interface[api’s]
  3. security enhancements: database encryption, more secure default settings, procedure enforcements
  4. Scalability: table partitioning, replication enhancements, and 64 bit support.


                     As sql is a common language for any RDBMS,ANSI committee provides a standard for SQL
  • The sql that follows the current standard for ANSI committee is called as ‘transact sql’ and sql server uses transact sql as its language
  • Sql is a non procedural or 4th generation language
  • Sql is not case sensitive
  • The commands of sql are classified into:

  1. data definition language[DDL]:
CREATE,ALTER ,DELETE


  1. data manipulation language[DML]

INSERT,MODIFY AND DELETE
  1. data query language[DQL]

SELECT
  1. data control language[DCL]:CONTROL DATA

GRANT AND REVOKE
  1. transaction control language[TCL]:MANAGE DATA

COMMIT,ROLLBACK,SAVE


Note:
  1. single sql can maintain maximum 32,767 databases
  2. databases are maintained by sqlserver

DATA TYPES IN SQL SERVER

INTEGER             tiny int—1  small int-2  int—4 big—8
Float                decimal(precision,scale)-5-17,float(p)-p<25-4,small money  4,money-8             
Character       char(n) fixed  length character—4000bytes,varchar(n) variablelengthchar—n>0  n<=4000
Nchar--4000
Nvarchar--4000
Text(n)-2gb
Ntext(n)—2 power 30 -1
Binary(n)-4000
Varbinary(n)—n>=14  n<4000
Image(n)-2 poer 31-1
Bit—true or false-1
Small date time-2   1st jan 1900 to 6th june 2069
Date time-4---1st jan 1753 to 31st dec9999

Other data types         
Sqlvariant-store any type of data
Table-a table itself
Xml-xml document
Timestamp-within a table if we declare then no need to give value it will be updated by db.
<code>


create database newdb
sp_helpdb "newdb"
use newdb
sp_renamedb 'newdb', 'hai'
drop database newdb
select * from newtable
</code]
creating a table
create table tablename(column1 datatype(width),col2 datatype(width) constaint specification,col3 datatype(width)-------);

CREATE TABLE
[code]
create table newtabel1(sno int,sname varchar(10),s1 int)
primary key

create table newtabel1(sno int primary key,sname varchar(10),s1 int)
[/code]
Insert


1…..insert into newtable values( 1,'hai',21)
2….insert into newtable (sno,s1) values(12,2)
3…insert into newtable values( 2,'myname',null)
select

select */column1,colum2,col3--- /expression [alias] from tabel1 [alias],[table2 [alias]--- n] [where <condition1> [and/or/not <condition2>---n] [order by <column1> asc\desc, <column2> asc/desc---n] [group by <expression>] [having <condition>]
[code]
select * from newtable
select sno,s2 from newtable
select sno,s1,s2,s1+s2 total from newtable

relational opertors in sql
>,<,>=,<=,<>,=
In(val1,val2)
NotIn(val1,val2)
Between<lowerbound> and <upperbound>
Not between<lb> and <ub>
Is null
Is not null
Like<pattern matching>
Not like<pm>

select sno,s1,s2,s1+s2 total from newtable where s1>20
select sno,s1,s2,s1+s2 total from newtable where s1>20
and s2<13
s select sno,s1,s2,s1+s2 total from newtable where sname=’nan’
select sno,s1,s2,s1+s2 total from newtabel where sname=’nan’ or sname=’hai’ or sname=’l’
select sno,s1,s2,s1+s2 total from newtable where sname in(‘lal’,’nan’)
select sno,s1,s2,s1+s2 total from newtable where sname not in (‘hai’)
select sno,s1,s2,s1+s2 total from newtable where s1 between 20 and 40
Like pattern matching cannot be used for numerics
select sno,s1,s2,s1+s2 total from newtabel where sname like ‘a%’




select sno,s1,s2,s1+s2 total from newtable where s1 is null
select sno,s1,s2,s1+s2 total from newtable where s1 is not null;
select sno,s1,s2,s1+s2 total from order by sname
select sno,s1,s2,s1+s2 total from newtableorder by sname, desc

[/code]
ALTER

Alter table tablename add/modify/delete columnname datatype(width)
[code]
alter table newtable add  s2 int
[/code]
alter table tablename delete column columnname


DELETE

Delete from tablename
Delete from table name where condition


UPDATE

Update <tablename> set <column>=value where condition
DROP

Drop table tablename

Creating a table by taking information from already created table


 Create table tablename as select statement
Create table exe as select * from emp where ename=’an’
RENAME

 Rename oldtable name to newtablename
<select statement>



Copying rows from one table to another table


Insert into tablename (colname,col2) from tabelname(col1,col2)

The source and destination tables have same datatype and width of the colunns



Constraints


1.primary key
2.Check
3. unique
4. notnull
5.default
6.foerign key
7.null

To add constraint for already created table
Alter table tablename add constraint constraintname constraintspecification(column)


Alter table emp add constraint pk_emp_eno primarykey(eno)

Alter table emp enable constraint pk_emp_eno

Alter table emp disable constraint pk_emp_eno

To drop comstraint

Drop constraint constraintname

Drop constraint pk_emp_en

UNIQUE

 It allows null vales
Create table emp(eno int primarykey, name varchar(20),sal float unique)
Create table emp(eno int primarykey, name varchar(20),check(sex in(‘m’,’f’,’M’,F’))
Create table emp(eno int primarykey, name varchar(20),age int check age between(18 to 50)

Notnull


Notnull with unique is equal to primary key
Create table emp(eno int primarykey, name varchar(20),age int notnull)

DEFAULT

Create table emp(eno int primarykey, name varchar(20),age int,town varchar(23) default ‘tirupati’)


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


PROCEDURE OF DEPLOYMENT IN .NET

DEPLOYMENT

  • After creating the application creating setup for the application and making this setup available on a cd or network resource or a website is called as deployment.
  • To create setup for your application open Ur application and then follow the sets:

  1.  within the ‘file menu—new—project   
    1. Within the new project dialog box choose ‘other’ project types and then ‘set up deployment’ and ‘set up project templet’ .
    2. After selecting the temp-let choose solution option as ‘add to solution’ and select OK.
  2. Immediately after setup project is added to the solution, file system of setup project will be opened.
  3. within the file system, ,3 folders are available::
    1. application folder: it is used to specify the files to be copied to the application folder during the installation.
                                                              i.      Click on application folder within the file-system to open it.
                                                            ii.      Right click within the application folder and then choose  ‘add project output’
                                                          iii.      Within the project output Daliaogue box, select every option and click on  OK  button, which add the exe file to ur project and any locationlised resources of Ur project to the application folder
                                                          iv.      If ur project refers to any private assemblies, the dll files of those assemblies must be added to the application folder. For this right click with in the application folder and then choose add—assembly option.
                                                            v.      Here in assembly choice browse tab and select all dll files of private assembly. And click ok
    1. users desktop::this is used to specify the shortcuts to be created on desktop during installation.
                                                              i.      One shortcut we can create on desktop is shortcut to the exe file of the project
                                                            ii.      For this open users desktop right click on it and choose create shortcut
                                                          iii.      Within the shortcut dialogue box by default application folder is opened.
                                                          iv.      Within this select ‘primary output’ and click ok
    1. users program menu: it is used to specify the shortcuts within the programs menu of the start menu during the installation
                                                              i.      first to create a folder for ur application within the programs menu right click within the users program menu and then choose add folder
                                                            ii.      within the folder right click and choose create shortcut within this folder
  1. within the file-system by right clicking on the file system on target machine and then choosing the add special folder option we can add the special folders like:
    1. fonts
    2. program files
    3. system
    4. windows and
    5. global assembly cache
  2. along with the file system, setup also provides other tools like :
    1. registry
    2. files types
    3. user interface
    4. custom actions and
    5. launch conditions
  3. open build menu and then choose ‘build setup project’ to build the setup project and create setup for ur application.