Click here to load reader

Learningcomputer.com SQL Server 2008 – Introduction to Transact SQL

Embed Size (px)

Citation preview

SQL Server Configuration Manager

Learningcomputer.comSQL Server 2008 Introduction to Transact SQLWhat is Transact SQL?It is pronounced as Transact SQL or Transact SEQUEL Transact SQL or TSQL is a powerful database language It provides programmatic functionality within the relational databases provided by Microsoft SQL SERVER and Sybase database products It is SQL-92 compliant as set by ANSI (American National Standards Institute)It can be broken down into two main areasDML (Data manipulation language) e.g. SELECT, INSERT ..DDL (Data definition language) e.g. CREATE TABLE, DROP DATABASE ..2Sample database AdventureWorks2008Adventure Works Cycles, the fictitious company on which the database is based on. It primarily sells bicycle and partsThe downloads can be found here http://www.codeplex.com/MSFTDBProdSamples/Release/ProjectReleases.aspx?ReleaseId=16040I had some issues running the download program and had to run this command from C:\ regsvr32 vbscript.dll After the download, I was able to run this script RestoreAdventureWorks2008.sql. This was found here C:\Program Files\Microsoft SQL Server\100\Tools\Samples I had to replace value of @source_path variable to bolded text above DML statements for todaySELECTINSERTUPDATEDELETE Mighty SELECT statement The SELECT statement forms the core of the SQL database languageMost commonly used SQL command by farYou use the SELECT statement to select or retrieve rows and columns from database tablesIt does not make any changes to the underlying data This statement can use a sub-select (sub query)The SELECT statement syntax contains five major clauses, generally constructed as follows

5SELECT statement syntaxSELECT FROM [WHERE ] [GROUP BY ] [HAVING ] [ORDER BY ];* Notice the bold code is required

6SELECT Example We will be using the Adventureorks2008 sample database for SQL Server Launch SQL Server Management Studio and connect to your local SQL instanceExpand the database tab and select Adventureorks2008Right click and select New QueryType the followingSELECT * FROM PERSON.PERSONWHERE LASTNAME='WOODIt should return 87 rows also known as records

7A little more on SELECTLets try SalesOrderHeader table with multiple conditionSELECT * FROM SALES.SALESORDERHEADERWHERE TERRITORYID=1 AND ORDERDATE < '2002-01-03'Quick way to copy data from one table to another is SELECT INTO. Why would you need this?SELECT * INTO HUMANRESOURCES.EMPLOYEE2FROM HUMANRESOURCES.EMPLOYEESQL OperatorsOperators are used to limit the number of results from the query. Also they are used for mathematical and logical operations. Here are a few types of operators.Standard Operators:= equal tonot equal to= greater than or equal to between used to show between two numbersLogical OperatorsAND used when both conditions are includedOR used when either of the condition is trueNOT opposite of the logical valueINSERT statement Inserts one or more new rows into the specified tableWhen you use the VALUES clause, only a single row is inserted. Typically used to insert single row of data. However INSERT can use a sub-select (sub query) to insert multiple records.

INSERT Syntax INSERT INTOtable-name [({column-name},...)] VALUES({literal},...) | select-statement}If you use a sub-select statement, the number of rows inserted equals the number of rows returned by the select statement Makes it easier to manage the permissions in your databases

INSERT Example We will be using the Person.Person tableFor BusinessEntityID, I had to insert a record into BusinessEntity for referential integrity, more on this laterRight click and select New QueryType the followingINSERT INTO PERSON.PERSON(BUSINESSENTITYID, PERSONTYPE, NAMESTYLE,FIRSTNAME, LASTNAME, EMAILPROMOTION, MODIFIEDDATE)VALUES (20778, 'EM', 0, 'KASH', 'MUGHAL', 0, GETDATE())This should insert one record into Person table

12UPDATE statement This is used to update data in the tablesUses a WHERE clause to seek the rows that need to be updatedCan use a sub-select (sub query) to update data from another underlying table In the absence of WHERE clause, all the records are updatedBe VERY careful with this one!

UPDATE Syntax In its simplest form, here is the syntaxUPDATE tablenameSET {column-name = { | NULL}},... [WHERE ] Notice the Where clause is optional (enclosed in []) however I would strongly recommend using it regularlyIf you use a sub-select statement, the number of rows inserted equals the number of rows returned by the select statement

UPDATE Example We will update the record that we just inserted into Person.Person table Right click and select new queryType the followingUPDATE Person.PersonSET FirstName='KASHEF'WHERE BusinessEntityID=20778This will update one record only

15And my favorite DELETE statement Used to delete data from tablesLike the Update statement uses the WHERE clause to locate the records to delete. In case of No WHERE clause, deletes all the records in the tableBe very careful with this one also!Remember there is no Undo or Control + Z in SQL Server!!Funny but TRUE story

DELETE Syntax DELETE FROM {table-name }[WHERE ];Notice how you do not need * in fact it will give you an error Where clause is optional (enclosed in []) however I would strongly recommend using it regularlyDelete statement can use a sub-select (sub query)In the absence of where clause deletes all rows, enough said

DELETE Example Expand the database tab and select AdventureWorks2008We will delete one row from Person table, the one we inserted earlierRight click and select new queryType the followingDELETE FROM PERSON.PERSONWHERE BUSINESSENTITYID=2077818Review SELECTINSERTUPDATEDELETE