Sei sulla pagina 1di 19

r SQL Server Management Studio 2008 Introduction Microsoft SQL Server is a RDBMS designed to run on platforms ranging from

laptops to large multiprocessor servers. SQL Server is commonly used as the backend system for websites and corporate CRMs and can support thousands of concurrent users. SQL Server comes with a number of tools to help you with your database administration and programming tasks. Its file extension .SQL. Database A database is a collection of data as well as programmes. OR Database is an organized collection of data or related information that are shared or used for multiple purposes. For example: Telephone directory, Students records, Result sheet, Population census etc. RDBMS It stands for Relational Database Management System. A database management system built on the concept of relational model is called relational database management system. A database management system is software that helps in creating and maintaining a database. It acts as the interface between the database and the user.

SQL It stands for Structured Query Language. SQL is a language used to communicate with database to perform certain operations. The SQL statements are not property of any individual company but a universal language developed for database. In SQL database program we can do create database, table, inserting records, update records, delete tables and records etc. Lesson :1| MsSQL Server Management Studio Management studio is the main administration console for SQL Server which enables us to create database objects (such as databases, tables, views etc) How to connect with an Object Explorer/ SQL Server 2008 Step 1: Click on Start button. Step 2: Click on Run. Step 3: Type SSMS and press Enter key. Step 4: Then the dialog box appears to connect with Server. Step 5: Type the server name as RECEPTION,Select authentication as SQL Server Authentication. Step 6: Type the user name as SA and password as aptech.

Sql Server Notes

Step 7: Finally, click on Connect.

Lesson :2| Database Create a Database Syntax: Create database <database_name> Example: Create database school Working with Database Syntax: Use <database_name> Example: Use school Note:sp_help --For displaying all the Tables of Database sp_help bill --For displaying the table structure of Table [Sp stands for Store procedure] Renaming Database Syntax:sp_renamedb oldname, newName Example:sp_renamedb School, Skool OR Syntax:alter database OldName modify name= newName

2|

By:-Anup

Sql Server Notes

Example: alter database Skool modify name= School To view database information Syntax:Sp_helpdb <database_name> Example:Sp_helpdb School Lesson :3| Table Data type in Sql server Datatypes numeric int tinyint smallint bigint decimal Description Functionally equivalent to decimal. Integer (whole number) data from -2^31 (-2,147,483,648) through 2^31 - 1 (2,147,483,647). Integer data from 0 through 255. Integer data from 2^15 (-32,768) through 2^15 - 1 (32,767). Integer (whole number) data from -2^63 (-9223372036854775808) through 2^63-1 (9223372036854775807). Fixed precision and scale numeric data from -10^38 +1 through 10^38 1. Example:create table datatype1(name varchar(20),addr text,sal decimal(10,2)) Floating precision number data from -1.79E + 308 through 1.79E + 308. Variable-length non-Unicode data with a maximum length of 2^31 - 1 (2,147,483,647) characters. Fixed-length non-Unicode character data with a maximum length of 8,000 characters. Variable-length non-Unicode data with a maximum of 8,000 characters. Date and time data from January 1, 1753, through December 31, 9999. Monetary data values from -2^63 (-922,337,203,685,477.5808) through 2^63 - 1 (+922,337,203,685,477.5807).

float text char varchar datetime money

/*Unicode is a character encoding system similar to ASCII. Unicode is the universal character encoding, maintained by the Unicode Consortium. This encoding standard provides the basis for processing, storage and interchange of text data in any language*/

3|

By:-Anup

Sql Server Notes

Creating Table Syntax:Create table <tablename>(fieldname1 datatype,fieldname2 datatype,fieldname3 datatype,fieldname4 datatype,); Example:create table customer ( dDate datetime, Custid varchar(25), Name varchar(25), Address varchar(50), salary money ) Inserting record into the table Syntax: insert into table_name values ('value1,value2,value3,..) Example:insert into customer values ( '2001/12/02', 'cust14', 'Rajesh', 'patan', 1000 ) Inserting record into selected Fields Syntax: insert into <table_name > (fieldname1,fieldname2,fieldname3,..) values ('value1,value2,value3,..) Example:Insert into office (Name, address, gender) values (Saloni, Patan, female) Displaying Records Syntax:Select *from <table_name> Example:Select * from Staff Retrieving all records from table Syntax:Select *from <tablename> Example:select*from office Retrieve selected column from selected field Syntax:Select field1,field2 from <table_name> Example:Select name, address from office

4|

By:-Anup

Sql Server Notes

Adding column in existing table Syntax:alter table <tablename> add <columnname> datatype; Example:alter table office add gender varchar(20); Deleting column Syntax:Alter table <table_name> drop column <coumn_name> Example:Alter table staff drop column name Renaming column Syntax:Sp_rename <'table_name.old_fieldname>,<new_field_name> Example: Sp_rename staff.name,User_name Changing Datatype Syntax:Alter table <table_name> alter column <column_name> <new_datatype> Example:Alter table staff alter column user_name varchar(50) Update data Syntax:Update <tablename> set fieldname='value' where fieldname='criteria' example:Update office set phoneno='5539522' where name='raj' View all table of database Sp_tables To display Table structure Syntax: Sp_help <table_name> Example:Sp_help staff Renaming Table Syntax:Sp_rename <old_table_name>, <new_table_name> Example:Sp_rename staff, member Deleting data (row) from table 1. Deleting All data Syntax:Delete from <table_name> Example:Delete from Staff 2. Delete data using where clause Syntax:Delete from <table_name> where fieldname= value Example:-

5|

By:-Anup

Sql Server Notes

Delete from Staff where name= saloni To view all user Table from database Select * from information_schema.tables where table_type= base table Select statement using where clause Syntax:Select * from <table_name> where <field_name>= value Example:Select * from staff where Name= Saloni Select * from staff where phone=9841257869 Lesson :4| Operators 1. Comparision Operators > -Greater Than < -Less Than >= -Greater Than Equals to <= -Less Than Equals to = -Equals to Syntax:Select * from staff where <field_name><operator>values Example:Select * from staff where roll>=12 2. And Operator Syntax:Select * from staff where <field_name1>= values and <field_name2>= values Example:Select * from staff where Name=Shahil and roll>12 3. Or Operator Syntax:Select * from staff where <field_name1>= values or <field_name2>= values Example:Select * from staff where Name=Shahil or roll>12 4. Not Operator Syntax:Select * from staff where not <field_name1>=value Example:Select * from staff where not Name=Shahil 5. Range Operator (between/notbetween) Syntax:Select * from staff where <field_name1> between range and range Example:Select * from staff where age between 25 and 35 Select * from staff where age notbetween 25 and 35 6.List Operator(In/Not in) Syntax:Select <field_name1>,< field_name2>,..from <table_name> where < field_name> in (value1,value2,..) Example:Select custid, name, phone from customer where address in ('patan','bhaktpur') Select custid, name, phone from customer where address not in ('patan','bhaktpur')

6|

By:-Anup

Sql Server Notes

Into Function Syntax:Select <field_name1>, < field_name2>, ..into <old_table_name> Example:Select Name, class, roll into Staff from student Order by Function (Sorting) Syntax:Select * from <table_name> order by <field_name> Example:Select * from student order by name Select *from customer order by name desc Select *from customer order by name asc Limiting Result sets using Top and percentage operator Syntax:Select top <number> *from <table_name> Example:Select top 10 *from customer Select top 2 *from customer order by name Select top 2 *from customer order by name desc Select top 2 *from customer order by name asc Eliminating Duplicates with Distinct keyword Syntax:Select distinct <field_name> from <table_name> Example:Select distinct Name from customer

<new_table_name>

from

Using the % Wildcard Display the staffs records whose Fname starts with "sa" Select * from staff where Fname like 'N%' Select * from staff where Fname like '%a' Select * from staff where Fname like '%S%' Using the _ Wildcard Display the staffs Last name that starts with any character, followed by "Ch" SELECT * FROM Staff WHERE lname LIKE '_ch' SELECT * FROM Staff WHERE lname LIKE '_hy' SELECT * FROM staff WHERE LName LIKE 'L_m_' Using the [charlist] Wildcard Display the staffs last name that starts with "b" or "s" or "p" SELECT * FROM staff WHERE L_Name LIKE '[bns]%' Display the staff's last name that does not begins with the following letters "b" or "n" or "s". SELECT * FROM staff WHERE L_Name LIKE '[^bns]%' Begins with J and the following letters is not a. Select * from staff where L_name like 'J[^a]%'

7|

By:-Anup

Sql Server Notes

View only Null Value Syntax:Select *from <table_name> Where <field_name> is Null Example:Select *from Customer Where Phone is Null Data integrity Data integrity, in terms of data and network security, is the assurance that information can only be accessed or modified by those authorized to do so. ... OR The condition that exists as long as accidental or intentional destruction, alteration, or loss of data does not occur. Lesson :6| Constraint Constraint is a check placed on the data to ensure data integrity. Type of constraint 1. Identity Constraint 2. Primary key Constraint 3. Unique Constraint 4. Foreign key Constraint 5. Null or Not null Constraint 6. Default Constraint 7. Check constraint 1. IDENTITY The IDENTITY property creates an identify column in a table. It generates unique system values automatically in as specified column. Syntax: Column_Name Datatype IDENTITY(Seed,INCREMENT) Example:Creating Table Using IDENTITY Create table TT(Id bigint identity(1,1),Fname varchar(45) constraint def default 'Sanjay') Adding IDENTITY In Existing Table Alter table <table_name> add [column_name] identity(Seed,increment) alter table books add BookId identity(1,1) 2. Primary key It Is a constraint that enforces entity integrity for a given column or columns through a unique index. Only one PRIMARY KEY constraint can be created per table.
Note:-In the Existing Table First U have 2 Apply Not null constraint in that field. As:alter table books alter column Bookid varchar(20) not null

Example:alter table books add constraint PK2 primary key (bookid)

8|

By:-Anup

Sql Server Notes

3. Default Constraint A default Constraint is created to provide a value for a column if the user does not give the value. A column can have only one value as a default value. Syntax: [constraint][constraint_name] default (expression) Creating Table Using Default Constraint Syntax:Create table <table_name>(Field_name [constraint_name] Default (expression))

datatype,

Field_Name

datatype

constraint

Example:Create table TT(Id bigint,Fname varchar(45) constraint def default 'Sanjay') Inserting Record Insert into TT values(1,Default) Adding Default Constraint in Existing Table Alter table Books add constraint defl default 'Word' for BookName

4. Foreign Key A foreign key column refers to the values of primary key column of another table or the same table. A FOREIGN KEY constraint is combination of one or more column of a table. Syntax: create table <table_name>(field_name datatype constraint [constraint_name] foreign key references (<table_name>,[field_name]),field_name datatype,.....) Example:create table HH(Id bigint constraint FK2 foreign key references staff (Id),Fname varchar(45)) alter table salary add constraint FK foreign key(Id) references staff (Id) ALTER TABLE MyChecking ADD CONSTRAINT ckMinBalance CHECK (Amount > $100.00) 5. Unique constraint A unique constraint is a rule that forbids duplicate values in one or more columns within a table. Unique and primary keys are the supported unique constraints. For example, a unique constraint can be defined on the supplier identifier in the supplier table to ensure that the same supplier identifier is not given to two suppliers. Add Unique Constraint in Exixting table Syntax:Alter table <table_name> add constraint <constraint_name> Unique (<field_name>) Example:Alter table book add constraint U_book unique (bookname)]\ 6. Null/Not Null constraint A Not Null constraint enforces that column will not accept null values Example:Create table customer (

9|

By:-Anup

Sql Server Notes

Name char(20) primary key, Class int not null, Address varchar(45) ) 7. Check constraint check constraint is a rule that specifies the values allowed in one or more columns of every row in a table. A constraint is optional, and can be defined using the CREATE TABLE or the ALTER TABLE statement. Syntax:Alter table <table_name> add contstraint <constraint_name> check (<field_name><operator><criteria>) Example 1:ALTER TABLE MyChecking ADD CONSTRAINT ckMinBalance CHECK (Amount > $100.00) Example 2:Create table student ( Rollno int unique, Name varchar(20), Address varchar(45), Age tinyint check(age>=15 and age<=50), Gender char(5) check(gender=m or gender=f) ) Add check constraint in Existing table Syntax:Alter table <table_name> add constraint <constraint_name> check (criteria) Example:Alter table customer add constraint cust_chk check (id between 100 and 1000) Displaying constraint in the Table Syntax:Sp_helpconstraint <table_name> Example:Sp_helpconstraint test Dropping Constraint Syntax:Alter table <table_name> drop constraint <constraint_name> Example:Alter table TT Drop constraint def COMPUTE Syntax:Select <field_name> <operator> <number> as <new_field_name> from <table_name> Example:select Roll,English,Math,Science,Nepali,Social,'Total'=English+Math+Science+Nepali+Social from Marksheet_info AGGREGATE FUNCTION Aggregate functions are use to generate summary values. They can be applied to all the rows in a table, or to the rows specified by a WHERE clause.

10 |

By:-Anup

Sql Server Notes

1. AVG AVG function returns the average of all the values in an expression. Example:select 'Average_Amount'=avg(Amount)from Bill_Format1 2. Count Count returns the number of non- null values in the expression provided. As another alternative you can use asterisk(*) as the COUNT expression. Using the asterisk eliminates specifying a particular column and will count all rows. Example:select 'No. of items'= count(Paticulars)from Bill_Format1 3. MAX Max returns the maximum value in an expression. Max ignore the NULL values. Example:select Maximum_Amount'=MAX(Amount)from Bill_Format1 4. MIN Min returns the minimum value in an expression. Example:select min(Amount)from Bill_Format1 5. SUM Sum returns the sum of all the values in an expression. Null values are ignored. Example:select net_amount=sum(Amount) from Bill_Format1 select sum(price) from items select itemname,sum(price) from items group by itemname having itemname='aa' Table 1 CREATE TABLE Student ( stRoll tinyint primary key, Fname varchar(20), Lname varchar(20), Gender char(6), Addr varchar(20), Phone bigint, Email_id varchar(20) ) Table 2 CREATE TABLE Fee ( rId char(4) primary key, stRoll tinyint, Paid_Amount decimal(10,2), dat varchar(10) ) Group By The Group by keyword is followed by a list of columns, known as the grouping columns. The Group by clause restricts the rows of the result set. There will be only one row for each different values in the grouping column.

11 |

By:-Anup

Sql Server Notes

Syntax: select [column_name] from <table_name> group by [column_name] Examples: select stRoll,sum(Paid_Amount)as Total_Fee_Paid from Fee group by stRoll HAVING Clause The HAVING Clause is used to filter rows after grouping them or for restricting rowes by applying aggregate functions in the Select statement.The HAVING clause sets conditions on the GROUP BY clause similar to the way 'WHARE' does with SELECT. The HAVING syntax is similar to the WHERE syntax, except that HAVING can contain aggregate function. Syntax: Select [column_name] from <table_name> group by [column_name] having (condition) Example: select stRoll,sum(Paid_Amount)as Total_Fee_Paid from Fee group by stRoll having stRoll=1 Lesson: 8| Join Join are used to retrieve data from two more tables based on logical relationships between the tables. A Join typically specifies foreign key relationship between the tables. The columns being joined must have same or comparable data types. Example:Select f.Rid,s.stRoll,Fname,Lname,Gender,Addr,Phone,Email_id,Paid_Amount,dat from Student as s join Fee as f on s.stRoll=f.stRoll Creating Join select f.Rid,s.stRoll,Fname,Lname,Gender,Addr,Phone,Email_id,Paid_Amount,dat from Student as s join Fee as f on s.stRoll=f.stRoll where Rid=R001

VIEW View is an alternate way of looking at data from one or more table(s) in the database. A view is a virtual table, usually created as subset of column or rows from one or more tables. The data is displayed directly from the table at the time of execution. Displaying All the views of current database Use:Select name from sysobjects where type='v' Creating View Syntax:Create view <viewname> as <sql_Statement> Example:Create view V1 as select * from staff Displaying Records using view Syntax:Select * from <view_name>

12 |

By:-Anup

Sql Server Notes

Example: Select * from v1 Select fname,lname,address from v1 Displaying Records using view Select * from v1 select fname,lname,address from v1 Deleting View Syntax: Drop view <viewname> Example:Drop view v1 Changing View Definition Syntax: Alter View <viewname> as <sql_Statement> Example:Alter view v1 as select Fname,lname,address from staff Renaming View Syntax: Sp_rename 'Old viewName' , 'New Viewname' Example:Sp_rename 'v1', 'view1' Adding Data in a table Using Veiw syntax: Insert into <viewname> <column_list> values <value_list> Example:Insert into v1 values (7,'Prakash','Thapa','KumariPati',5536520,'Male','05/08/1990') Creating Views Using Join Example: create view VJ as select I.ItemId,s.Solditem,Qty as Itemqty,S.soldqty, (I.Qty-S.soldqty) as RemainQty from items as I right outer join sales as s on I.itemId=s.ItemId select * from vj Displaying View Structure Syntax:Sp_helpText <viewname> Example:sp_helptext vj Modifying Data in a Table using View Syntax:Update <viewname> set [column_name]= <expression> where <condition> Example:Update view1 set name=Saloni where custid=cust12

13 |

By:-Anup

Sql Server Notes

Creating Encryption on view Syntax:Create view <view_name> with encryption as <sql_Statement> Example:Create view customview with encryption as select custid,name from customer Create VIEW myView WITH ENCRYPTION AS SELECT * from Employee INDEX An index allows the database program to find data in a table without scanning through the entire table. It is use to arrange the records in ascending order and makes it flexible while searching the data in a table. Creating Index Syntax:Create index index_name on <table_name> (column_name) Example:Create index inxstRoll On Fee(stRoll) TYPES OF INDEX 1. Clustered index 2. Non- clustered index 3. unique clustered index 4. unique non-clustered index A.Clustered Index: Clustered index is an index in which the logical or indexed order of the key value is the same as the physical stored order of the corresponding rows that exist in a table. Syntax:Create clustered index [indexname] on customer(ColumnName) B. Non-Clustered Index: Non-Clustered index is an index in which the logical order of the index does not match the physical order of the rows on disk. Syntax:Create nonclustered index [indexname] on TableName(ColumnName) C.Unique Clustered Index It creates a cluster index on the column as well as it doesnt allow the duplicate value to be entered on that column. Syntax:create unique clustered index [index_name] on table_name(field_name) D. Unique non-Clustered Index It creates a non-cluster index on the column of the table and it also doesnt allow the duplicate value to be entered on that column. Syntax:create unique clustered index [index_name] on table_name(field_name)
Note:1. Primary key constraint automatically creates a unique clustered index on the column. 2. Default index is non-clustered index, if index is not specified.

Viewing an Index Syntax: -

14 |

By:-Anup

Sql Server Notes

Sp_helpindex <table_name> Example:sp_helpindex customer Renaming Index Syntax:sp_rename 'Table_name.oldindex_name','table_name.newindex_name' Example:sp_rename 'customer.inx_id','customer.index_id' Deleting Index Syntax:Drop index <table_name.index_name> Example:Drop index customer.index_id Lesson :11| Store Procedure Store Procedure is precompiled collection of Transact-SQL Server statement stored under a name and processed as unit.

Creating Store procedures Syntax:1.Create Procedure <procedures_name> As <SQL Statement>

Example:1.Create Procedure proce1 As Select*from Customer Running Procedures Syntax:1.execute <procedures_name> 2. <procedures_name> Example:1.execute proce1 2. proce1 Drop Procedure Syntax:drop procedure <procedures_name> Example:drop procedure <procedures_name>

15 |

By:-Anup

Sql Server Notes

Creating store procedure with parameter Syntax:Create Procedure <Procedure_name> @<var_name> <datatype> As <Sql_Statement> Example:Create Procedure S1 @Salary int As Select * from customer where salary>=@salary Execute the Query Syntax:execute <Procedure_name> <Value> More Example:-

16 |

By:-Anup

Sql Server Notes

Stored Procedure with Default Value Create Procedure StaffBySalary @Salary int=15000 as Select * from Staff where Salary<=@Salary -------------------------------------------------------------------Procedure with variable create proc p1 @n1 smallint,@n2 smallint as declare @sm int select 'Numbers are : ', @n1,@n2 set @sm=@n1+@n2 select 'Sum is : ', @sm ------------------------------------------------------------------exec p1 10,20 ----------------------------------------------------------------------------

17 |

By:-Anup

Sql Server Notes

Modifying Procedure Example:A. Create Create proc addnum @a float,@b float As declare @c float set @c=@a+@b print @c B. Run Execute addnum 12,12 C. Modify Alter proc addnum @a float,@b float As declare @c float set @c=@a+@b print 'the sum of '+convert(varchar (20),@a)+' and '+ convert(varchar(10),@b)+' is '+ convert(varchar(20),@c) D. Run Execute addnum 12,12

Trigger A trigger is a database object that is attached to a table. In many aspects it is similar to a stored procedure. As a matter of fact, triggers are often referred to as a "special kind of stored procedure." The main difference between a trigger and a stored procedure is that the former is attached to a table and is only fired when an INSERT, UPDATE or DELETE occurs. You specify the modification action(s) that fire the trigger when it is created. Creating trigger Syntax:Create trigger <trigger_name> On <table_name> For <insert/ Update/Delete> As <Sql_statement> Example:A.Insert create trigger Tr1 on Customer for insert As If((select salary from inserted)<= 1000) begin print'Bill Must be greater then 1000' rollback transaction end else

18 |

By:-Anup

Sql Server Notes

print 'Data inserted' B.Update 1.create trigger table_update_trig on emp for update as if(select salary from inserted)<5000 begin print 'The salary cannot be less than 5000' rollback transaction end 2.create trigger col_update_trig on emp for update as if update (age) begin print 'You cannot update the age field' rollback transaction end

19 |

By:-Anup

Potrebbero piacerti anche