-->

Monday, September 22, 2014

How to use Constructs in Batches for Conditional Execution: SQL

SQL Server allows you to use programming constructs in the batches for conditional execution of statements. For example, you need to retrieve data based on a condition. If the condition is not satisfied, a message should be displayed.

The SQL Server allows you to use the following constructs to control the flow of statements:

  • IF…..ELSE statement
  • CASE statement
  • WHILE statement

Using the IF….ELSE Statement

You can use the IF…..ELSE statement for conditional execution of SQL statements. A particular action is performed when the given condition on evaluates to TRUE and another action is performed when the given condition evaluates to FALSE.
The syntax of IF….ELSE statement is:

IF Boolean_expression
{sql_statement | statement_block}
ELSE
{sql_statement | statement_block}]
Where,

  • Boolean_expression specifies the condition that evaluates to either TRUE or FALSE. Sql_statement specifies a T-SQL statement.
  • Statement_block is a collection of T-SQL statements.

The following example retrieves the pay rate of an employee from the EmployeePayHistory table to a variable, @Rate. The value of the @Rate variable is compared with the value 15 by using the <(less than) comparison operator. Based on the condition, different messages are displayed.

DECLARE @Rate money
SELECT @Rate = Rate FROM HumanResources.EmployeeHistory
WHERE EmployeeID = 23
IF @Rate < 15
PRINT ‘Review of the rate is required’
ELSE
BEGIN
PRINT ‘Review of the rate is not required’
PRINT ‘Rate =’
PRINT @Rate
END
GO

In the preceding example, the IF statement checks if the rate variable is storing a value less than 15. If the result is true, the PRINT statement displays “Review of the rate is required” else it displays “Review of the rate is not required”. Further, the next PRN statement displays the value of the rate.

Consider another example, where a check is performed to see the existence of the sales department. If the Sales department exists, all the details are displayed otherwise, a user-defined message is displayed.

IF EXISTS (SELECT * FROM HumanResources.Department WHERE Name = ‘Sales’)
BEGIN
SELECT * FROM HumanResources.Department WHERE Name = ‘Sales’
END
ELSE
PRINT ‘Department details not available’
GO

Sunday, July 20, 2014

How to Perform Searching Data by Using a Full-Text Search

After the full-text index has been created on a table, you can query the table by using the full-text predicates. The full-text predicates are used to specify how the search string should be searched in the table.
Predicates can be used to enhance the search so that the result have so focus on the search criteria. Sql programming have a list of predicates to be used.

The following predicates can be used while performing the full-text search:

FREETEXT: When the search criteria are given, FREETEXT searches for any variation of a word or a group of words given in the search column. FREETEXT is used for the prefix searches.
Considering the previous scenario of the bike racing competition, you can use the FREETEXT predicate to obtain the desired output, as shown in the following statement:

SELECT Description FROM Production.ProductDescription WHERE FREETEXT (Description, ‘race winners’)

CONTAINS: This predicate is used in queries when you want to search for a specific phrase or for the exact match. It also searches for the proximity of words within a text. For example, you can use the following statement to search for the words ‘Ride’ near the word ‘Bike’ in the ProductDescription table:

SELECT Description FROM Production.ProductDescription
WHERE CONTAINS (Desctiption, ‘ride NEAR bike’)

Populating the Full-Text Index in Search: SQL Server

After creating the full-text index, you need to populate it with the data in the columns enabled for full-text support. The SQL Server full-text search engine populates the full-text index through a process called population. Population involves filling the index with words and their location in the data page. When a full-text index is created, it is populated by default. In addition, the SQL Server automatically updates the full-text index as the data is modified in the associated tables.

However, the SQL Server does not keep a list of changes made to the indexed data when the CHANGE_TRACKING option is off. This option is specified while creating the full-text index by using the CREATE FULLTEXT INDEX statement.

If you do not want the full-text index to be populated when it is created using the CREATE FULLTEXT INDEX statement, then you must specify NO POPULATION along with the CHANGE TRACKING OFF option. To populate the index, you need to execute the ALTER FULLTEXT INDEX command along with the START FULL, INCREMENTAL, or UPDATE POPULATION clause.

For example, to create an empty full-text index on the ProductDescription table, you can execute the following statement:

CREATE FULLTEXT INDEX ON Production. ProductionDescription (Description)
KEY INDEX PK_ProductDescription_ProductDescriptionID
WITH CHANGE_TRACKING OFF, NO POPULATION

To populate the index you need to execute the following statement:
ALTER FULLTEXT INDEX ON Production. ProductDescription START FULL POPULATION

The preceding statement will populate the full-text index created on the ProductDesctiption table.

Similar to regular SQL indexes, full-text indexes can also be updated automatically as the data is modified in the associated tables. This repopulation can be time-consuming and adversely affect the usage of resources of the database server during periods of high database activity. Therefore, it is better to schedule repopulation of full-text indexes during periods of low database activity. You can specify the following types of full-text index population methods to repopulate the index:

Full Population

You can use this method when you need to populate the full-text catalog or the full-text index for the first time. After that, you can the maintain the indexes by using change tracking or incremental populations.
During a full population of a full-text catalo, index entries are built for all the rows in all the tables covered by the catalog. If a full population is requested for a table, index entries are built for all the rows in that table.

Change Tracking-Based Population

The SQL Server maintains a record of the rows that have been modified in a table set up for full-text indexing. These changes are propagated to the full-text index.

Incremental Timestamp-Based Population

The incremental population method updates the full-text index with the data that has been changed since the last time the index was refreshed. For an incremental population refresh to work, the indexed table must have a column of the timestamp data type. If a table does not have a column of the timestamp data type, then only a full population refresh can be done.

Configuring Full-Text Search in SQL Server

The full-text query feature in the SQL Server enables users to search for a wide range of text in the SQL tables. Consider an example. The sales management team of AdventureWorks, Inc. makes frequent searches on the ProductDescription table to develop marketing strategies. The search is based on the data stored in the Description column of the table.

A bike racing competition is scheduled to begin in Texas. The sales manager of AdventureWorks wants to see the details of all the bikes that are related to racing, so that a marketing strategy can be designed to increase the sale of these bikes. Specifically, he wants a list of all the bikes that have the keyword ‘race winner’ in the description.

As the data is large, the search query takes a long time to retrieve data from the table. In this scenario, you can apply a full-text index on the Description column of the ProductDescription table to improve the speed of searching.

To retrieve the required details by using full-text search, you need to configure full-text search on the database. For this, you need to perform the following tasks:
  • Enable the full-text search in the database.
  • Create a full-text catalog.
  • Create a unique index.
  • Create a full-text index.
  • Populate the full-text index.

Enabling the Full-Text Search in the Database

Before using the full text search feature of the SQL Server, you need to enable the database using the following statement:
USE AdventureWorks
GO
Sp_fulltext_database enable
GO

Creating a Full-Text Catalog

A full-text catalog serves as a container to store full-text indexes. After enabling the full text search, you need to create a full-text catalog. A full-text catalog is a container that contains full-text indexes. A full-text catalog may have multiple full-text indexes. You can create a full-text catalog by using the following command:
CREATE FULLTEXT CATALOG cat1 AS DEFAULT

Creating a Unique Index

After creating the full-text catalog, you need to identify a unique index on the table. This unique index will be mapped to the values in the full-text index. You can use an existing unique index defined on the table, or create a new one. For example, you can create a unique index on the Production.ProductDescription table, as shown in the following statement:

CREATE UNIQUE INDEX Ix_Desc ON Production.ProductDescription
(ProductDescriptionID)

Creating a Full-Text Index

After you have created the full-text catalog and a unique index, you can create a full-text index on the table. A full-text index stores information about significant words and their location within a given column. You can use this information to compute full-text queries that search for rows with particular words or combinations of words. Full-text indexes can be crated on the base tables but not on the views or the system tables.

There are certain words that are used often and may hinder a query. These words are called noise words and are excluded from the search string. For example, if you search string is “Who is the governor of California”, a full-text search will not look for words, such as ‘is’ and ‘the’. Some noise words are a, an, the, and are.

Based on the preceding scenario, you can create a full-text index on the ProductionDescription table. This index is based on the lx_desc index created earlier on the Description column of the table.
Note: You can also create full-text index in the Object Explorer window by right-clicking the table, on which you need to create the full-text index, and selecting Full-Text index-Define Full-Text Index.

Altering, Dropping and Renaming Views in SQL Server

In addition to creating view in sql server, database developer also need to manage them. Management of a view includes altering, dropping, or renaming described below.

Altering views

If you define a view with a SELECT * statement and then alter the structure of the underlying tables by adding columns, the new columns do not appear in the view. Similarly, when you select all the columns in a CREATE VIEW statement, the columns list is interpreted only when you first create the view. To add new columns in the view, you must alter the view.

You can modify a view without dropping it. This ensures that permissions on the view are not lost. You can modify a view without affecting its dependent objects. To modify a view, you need to use the ALTER VIEW statement. The syntax of the ALTER VIEW statement is:

ALTER VIEW view_name [ (column_name) ]
[WITH ENCRYPTION]
AS select_statement
[WITH CHECK OPTION]
Where,

  • View_name specifies the view to be altered.
  • Column_name specifies the name of the column(s) to be used in a view.
  • WITH ENCRYPTION option enerypts the text of the view in the syscomments view.
  • AS specifies the action to be performed by the view.
  • Select_statement specifies the SELECT statement that defines a view
  • WITH CHECK OPTION forces the data modification statements to follow the criteria given in the SELECT statement.

For example, you created a view to retrieve selected data from the Employee and EmployeeDepartmentHistory tables. You need to alter the view definition by including the LoginID attribute from the Employee table.

To modify the definition, you can write the following statement:

ALTER VIEW vwEmployeeDepData
AS
SELECT e.EmployeeID, LoginID, MaritalStatus, DepartmentID
FROM HumanResources.Employee e JOIN
HumanResources.EmployeeDepartmentHistory d
ON e.EmployeeID = d.employeeID

The preceding code alters the view definition by including the LoginID attribute from the Employee Table.

Dropping Views

You need to drop a view when it is no longer required. You can drop a view from a database by using the DROP VIEW statement. When a view is dropped, it has no effect on the underlying table(s). Dropping a view removes its definition and all the permissions assigned to it.

Further, if you query any view that references a dropped table, you receive an error message. Dropping a table that references a view does not drop the view automatically. You have to use the DROP VIEW statement explicitly.
The syntax of the DROP VIEW statement is:  DROP VIEW view_name

For example, you can use the following statement to remove the vwEmployeeDepData view:
DROP VIEW vwEmployeeDepData

The preceding statement will drop the vwEmployeeDepData view from the database.

You can drop multiple views with a single DROP VIEW statement. The names of the view that need to be dropped are separated by commas in the DROP VIEW statement

Renaming Views

At times, you might need to change the name of a view. You can rename a view without dropping it. This ensures that permissions on the view are not lost. A view can be renamed by using the sp_rename system stored procedure.
The syntax of the sp_rename procedure is:  Sp_rename old_viewname, new_viewname
Where,

  • Old_viewname is the view that needs to be renamed.
  • New_viewname is the new name of the view.

For example, you can use the following statement to rename the vwSal view:
Sp_rename vwSal, vwSalary

The preceding command renames the vwSal view as vwSalary.

While renaming views, you must ensure the following:

  • The view must be in the current database.
  • The new name for the view must follow the rules for identifiers.
  • The view can only be renamed by its owner.
  • The owner of the database can also rename the view.

Tuesday, May 13, 2014

How to Update Data in tables: SQL

Programmer need to modify the data in the database when the specifications of a customer, a client, a transaction, or any other data maintained by the organization undergo a change.

For example, if a client changes his address or if the quantity of a product ordered is changed, the required changes need to be made to the respective rows in the tables. You can use the UPDATE statement to make the changes. Updating ensures that the latest and correct information is available at any point of time. One column of a row is the smallest unit of an update.

You can update data in a table by using the UPDATE DML statement. The syntax of the UPDATE statement is:

UPDATE table_name SET column_name = value [, column_name = value]
[FROM table_name]
[WHERE condition]
Where,

  • Table_name specifies the name of the table you have to modify.
  • Column_name specifies the columns you have to modify in the specified table.
  • Value specifies the value(s) with which you have to update the column(s) of the table. Some valid values include an expression, a column name, and a variable name. The DEFAULT and NULL keywords can also be supplied.
  • FROM table_name specifies the table(s) that is used in the UPDATE statement.
  • Condition specifies the rows that you have to update.

Guidelines for Updating Data

You need to consider the following guidelines while updating data:

  • An update can be done on only one table at a time.
  • If an update violates integrity constraints, then the entire update is rolled back.

The following statement updates the AddressLine2 attribute of AddressID 104

UPDATE Address
SET AddressLine2 = ‘Plaza Palace’
WHERE AddressID = 104

Consider another example where you need to update the Title of an employee, Lynn Tsoflias to ‘Sales Executive’, in the Employee table. To perform this task, you need to refer to the contact table to obtain the Contact ID. You can update the details by using the following statement:

UPDATE HumanResources.Employee SET Title = ‘Sales Executive’
FROM HumanResources.Employee e, Person.Contact c
WHERE e.contactID = c.ContactID
AND c.FirstName = ‘Lynn’ and c.LastName = ‘Tsoflias’

When the preceding command is executed, the Title will be changed to ‘Sales Executive’.

Delete data from database and related table.
© Copyright 2013 Computer Programming | All Right Reserved