SQL Server - Bài
Trang 2Overview of Transact-SQL
Based on AINSI SQL 92 standard
Composing of three categories
Data Manipulation Language (DML)
Data Definition Language (DDL)
Having some Microsoft specific extensions
Beyond relational data
net framework integration
Trang 4Select Data
from the exit table is:
select <the items >
from <name of table>
where <conditions>
Trang 5Select Data
You can change the name of the items in the table:
Trang 6Select Data
You can insert some items as following:
Trang 7Select
Example a function ‘count’ to count the columns of the table:
Trang 8Select Data
You can use some functions or some operations in the Select Statement:
Trang 9Select Data
Trang 10The Time functions
Trang 11DATEPART(YY,g etdate())
- DATEDIFF(X,Y,Z )
- DAY(),MONTH(), YEAR()
Select Data
Maths String Time
Trang 13Oder by Compute For
Into
Having
With
Except , Intersect
Union
Option
Trang 14Select-With statement
Specifies a temporary named result set, known as a common table expression (CTE)
Trang 15Select-Order by
- You can arrange the result follow the first letter by using the order by statement:
Trang 17Select – multiple tables
Inner join:
Trang 18Select-multiple tables
- When you select from more than 1 table, you can use the join…on statement or you can use the cross join statement With the cross join statement, you don’t have to have to
relative condition between the tables and the result is all the Objects:
Trang 19Select-multiple tables
Trang 21Select-multiple tables
Trang 22more tables:
Trang 23Select-Group by
Specifies the groups into which output rows are to be placed If aggregate functions are included in the SELECT clause <select list>, GROUP BY calculates a summary value for each group
Trang 24 Specifies a search condition for a group or an aggregate
HAVING is typically used in a GROUP BY clause When GROUP BY is not used, HAVING behaves like a WHERE clause
Trang 25Microsoft
Trang 26 INTERSECT returns any distinct values that are returned by both the query
on the left and right sides of the INTERSECT operand.
Trang 27Select-except
EXCEPT returns any distinct values from the left query that are not also found on the right query
Trang 28Select-Compute by
Generates totals that appear as additional summary columns at the end of the result set When used with BY, the COMPUTE clause generates control-breaks and subtotals in the result set You can specify COMPUTE BY and COMPUTE in the same query
Trang 29Select-Compute by
Trang 30Select-For clause
FOR clause is used to specify either the BROWSE or the XML option BROWSE and XML are unrelated options
Trang 31Select-For clause
Trang 32Insert
The simple syntax for Insert statement is:
INSERT INTO<table(x,y,…)>
VALUES(a,b,…)
Trang 33Insert
- You can insert some values into the table, and you have to insert all the value not null, and the primary key:
Trang 34Insert
Trang 35Insert
If you don’t insert all the column not null, the process will terminate
Trang 36- You can create a new table and insert the values into that table
Trang 37Insert
Trang 38- Inserting data into a unique identifier column by using NEWID()
Trang 39Insert
- Inserting data into a table through a view
Trang 40Insert
Trang 42- Using DELETE on the current row of a cursor
Trang 43Delete
- Using DELETE based on a subquery and using the SQL extension
Trang 44- Using DELETE with the TOP clause
Trang 45Delete
Using DELETE with the OUTPUT clause
Trang 47Update
- Using UPDATE with the FROM Clause
Trang 48- Using the UPDATE statement with information from another table
Trang 49Update
- Before :
Trang 50 After
Trang 51Fulltext Search
Full-Text Search Architecture
Administering Full-Text Search
Querying SQL Server Using Full-Text Search
Trang 52Overview
Trang 53Overview
The architecture consists of the following processes:
Microsoft Full-Text Engine for SQL Server process (Msftesql.exe)
Microsoft Full-Text Engine Filter Daemon process (Msftefd.exe)
Trang 54Full-Text Search Terminology
Trang 55Administering Full-Text Search
The system stored procedures that are used to implement and query full-text indexes.
DENY permission [ , n ] ON FULLTEXT CATALOG :: full-text_catalog_name TO
database_principal [ , n ] [ CASCADE ] [ AS denying_principal ]
Trang 56Administering Full-Text Search
Full-text administration can be separated into three main tasks:
Creating/altering/dropping full-text catalogs
Creating/altering/dropping full-text indexes
Scheduling and maintaining index population
Trang 57Administering Full-Text Search
Full-text indexes Regular SQL Server indexes
Stored in the file system, but
administered through the database.
Stored under the control of the database
in which they are defined.
Only one full-text index allowed per
table. Several regular indexes allowed per table.
Addition of data to full-text indexes,
called population, can be requested
through either a schedule or a specific
request, or can occur automatically with
the addition of new data.
Updated automatically when the data upon which they are based is inserted, updated, or deleted.
Grouped within the same database into
one or more full-text catalogs. Not grouped.
Trang 58Guidelines in administering full-text indexes
Like regular SQL Server indexes, full-text indexes can be automatically updated as data is modified in the associated tables Alternatively, you can repopulate full-text indexes manually
at appropriate intervals, but this can be time-consuming and resource-intensive Therefore, index updating is usually performed as an asynchronous process that runs in the background during periods of low database activity.
Tables with the same update characteristics (such as small number of changes versus large number of changes, or tables that change frequently during a particular time of day) should be grouped together and assigned to the same full-text catalog By setting up full-text catalog population schedules in this way, full-text indexes stay synchronous with the tables without adversely affecting the resource usage of the database server during periods of high database activity.
It is important to plan the placement of full-text indexes for tables in full-text catalogs When you assign a table to a full-text catalog, consider the following guidelines:
Trang 59Guidelines in administering full-text indexes (2)
Always select the smallest unique index available for your full-text unique key (A 4-byte, integer-based index is optimal.) This reduces the resources required by Microsoft Search service in the file system significantly If the primary key is large (over 100 bytes),
consider choosing another unique index in the table (or creating another unique index) as the full-text unique key Otherwise, if the full-text unique key size exceeds the maximum size allowed (900 bytes), full-text population will not be able to proceed.
If you are indexing a table that has millions of rows, assign the table to its own full-text catalog.
Consider the amount of change occurring in the tables being full-text indexed, as well as the number of table rows If the total number of rows being changed, together with the numbers of rows in the table present during the last full-text population, represents
millions of rows, assign the table to its own full-text catalog.
Trang 60Guidelines in administering full-text indexes (3)
After the word breaker-routine has a list of valid words for a row within a column, the full-text engine calculates tokens to represent the words A token is simply a
compressed form of the original word that saves space and ensures that full-text
indexes can be created in as compact a form as possible.
The full text-text functionality then builds all tokens in a column into inverted, stacked, compressed structure within a file that is used for search operations This unique structure allows ranking and scoring algorithms to efficiently satisfy possible queries.
Trang 61Querying SQL Server Using Full-Text Search
Full-Text query keywords
FREETEXT
FREETEXTTABLE
CONTAINS
CONTAINSTABLE
Trang 62Querying SQL Server Using Full-Text Search
FREETEXT
FREETEXT ( { column_name | (column_list) | * } , 'freetext_string' [ ,
LANGUAGE language_term ] )
SELECT ProductDescriptionID, Description FROM Production.ProductDescription
WHERE [Description] LIKE N'%bike%';
SELECT ProductDescriptionID, Description FROM Production.ProductionDescription WHERE FREETEXT(Description , N’bike’); Must be UNICODE Otherwise prevents a query optimizer from parameter sniffing
Trang 63Querying SQL Server Using Full-Text Search
Trang 64Querying SQL Server Using Full-Text Search
FREETEXTTABLE
FREETEXTTABLE (table , { column_name | (column_list) | * } , 'freetext_string'
[ ,LANGUAGE language_term ] [ ,top_n_by_rank ] )
The FREETEXTTABLE version of the previous FREETEXT query would look like this:
SELECT PD.ProductDescriptionID, PD.Description, KEYTBL.[KEY], KEYTBL.RANK FROM Production.ProductDescription AS PD
INNER JOIN FREETEXTTABLE()Production.ProductDescription, Description, N’bike’)
AS KEYTBL ON PD.ProductDescriptionID = KEYTBL.[KEY]
Trang 65Querying SQL Server Using Full-Text Search
CONTAINS
CONTAINS ( { column_name | (column_list) | * } , '< contains_search_condition
>' [ , LANGUAGE language_term ] ) < contains_search_condition > ::= { <
simple_term > | < prefix_term > | < generation_term > | < proximity_term > | <
weighted_term > } | { ( < contains_search_condition > ) [ { < AND > | < AND NOT
> | < OR > } ] < contains_search_condition > [ n ] } < simple_term > ::= word |
" phrase " < prefix term > ::= { "word * " | "phrase *" } < generation_term > ::=
FORMSOF ( { INFLECTIONAL | THESAURUS } , < simple_term > [ , n ] ) <
proximity_term > ::= { < simple_term > | < prefix_term > } { { NEAR | ~ }
SELECT ProductDescriptionID, Description FROM Production.ProductDescription
WHERE CONTAINS(Description, N'bike');
SELECT ProductDescriptionID, Description FROM Production.ProductDescription
WHERE CONTAINS(Description, N'''bike*'''):
Trang 66Querying SQL Server Using Full-Text Search
SELECT ProductDescriptionID, Description FROM Production.ProductDescription
WHERE CONTAINS(Description, N' FORMSOF (INFLECTIONAL, bike) ');
SELECT ProductDescriptionID, Description FROM Production.ProductDescription
WHERE CONTAINS(Description, N' FORMSOF (THESAURUS, bike) ');
Word proximity is a common way of searching documents for multiple keywords or phrases This type of query uses the NEAR(~) keyword The closer words are to each other, the better the match for these types of queries The proximity is used as a part of RANK calculation for rows matching the search criteria This keyword is rarely used with the CONTAINS predicate because the rank of matched results cannot be evaluated directly.
SELECT ProductDescriptionID, Description FROM Production.ProductDescription
WHERE CONTAINS(Description, N'mountain NEAR bike');
SELECT ProductDescriptionID, Description FROM Production.ProductDescription
WHERE CONTAINS(Description, N'mountain ~ bike');
SELECT ProductDescriptionID, Description FROM Production.ProductDescription
WHERE CONTAINS(Description, 'ISABOUT (mountain weight(.8), bike weight (.2) )');
Trang 67Querying SQL Server Using Full-Text Search
The CONTAINSTABLE function has the same capabilities as the CONTAINS function
However, like the FREETEXTABLE function, it returns a rowset that contains a RANK and
a KEY column that can be used to return the best matches to a search.
CONTAINSTABLE ( table , { column_name | (column_list ) | * } , ' < contains_search_condition
> ' [ , LANGUAGE language_term] [ ,top_n_by_rank ] ) < contains_search_condition > ::=
{ < simple_term > | < prefix_term > | < generation_term > | < proximity_term >
| < weighted_term > } | { ( < contains_search_condition > ) { { AND | & } | { AND
NOT | &! } | { OR | | } } < contains_search_condition > [ n ] } < simple_term > ::=
word | " phrase " < prefix term > ::= { "word * " | "phrase *" } < generation_term > ::= FORMSOF ( { INFLECTIONAL | THESAURUS } , < simple_term > [ , n ] ) <
proximity_term > ::= { < simple_term > | < prefix_term > } { { NEAR | ~ } { <
simple_term > | < prefix_term > } } [ n ] < weighted_term > ::= ISABOUT ( { { <
simple_term > | < prefix_term > | < generation_term > | < proximity_term > }
[ WEIGHT ( weight_value ) ] } [ , n ] )
Trang 68Querying SQL Server Using Full-Text Search
Used correctly, will produce more specific, relevant results
Better performance – LIKE queries are designed for small amounts of text data, full-text search scales to huge documents
Provides ranking of results
Search through the content in a text-intensive, database driven website, e.g a knowledge base
Search the contents of documents stored in BLOB fields
Perform advanced searches
e.g with exact phrases - "to be or not to be" (however needs care!)
e.g Boolean operators - AND, OR, NOT, NEAR
Trang 69Writing FTS terms
The power of FTS is in the expression which is passed
to the CONTAINS or CONTAINSTABLE function
Several different types of terms:
Trang 70Simple terms
Trang 71 matches local, locally, locality
CONTAINS(Column, ' "local wine*" ')
matches "local winery", "locally wined"
Trang 74 Supposed to match synonyms of search terms – but the thesaurus seems to be very limited
Does not match plurals
Not particularly useful
Trang 75Proximity terms
Syntax
CONTAINS(Column, 'local NEAR winery')
CONTAINS(Column, ' "local" NEAR "winery" ')
Matches words which are NEAR each other
Terms on either side of NEAR must be either simple or proximity terms
Trang 76Weighted terms
Each word can be given a rank
Can be combined with simple, prefix, generation and proximity terms
performance weight(.8), comfortable weight(.4) )')
FORMSOF(INFLECTIONAL, "performance") weight (.8), FORMSOF(INFLECTIONAL, "comfortable") weight (.4)
Trang 77Microsoft