Monday, 30 March 2015

SQL Server Constraints

Constraints : Constraints are some rules that enforce on the data to be enter into the database table. Basically constraints are used to restrict the type of data that can insert into a database table.Constraints can be defined in two ways:

Column Level : The constraints can be specified immediately after the column definition with the CREATE TABLE statement. This is called column-level constraints.
Table Level : The constraints can be specified after all the columns are defined with the ALTER TABLE statement. This is called table-level constraints.

Types of SQL Constraints :

Primary Key Constraints : Primary Keys constraints prevents duplicate values for columns and provides unique identifier to each column, as well it creates clustered index on the columns.

Create Table Statement  to create Primary Key :

  1. Column Level

USE AdventureWorks2008
GO
CREATE TABLE Products
(
ProductID INT CONSTRAINT pk_products_pid PRIMARY KEY,
ProductName VARCHAR(25)
);
GO

  1. Table Level

CREATE TABLE Products
(
ProductID INT,
ProductName VARCHAR(25)
CONSTRAINT pk_products_pid PRIMARY KEY(ProductID)
);
GO

Alter Table Statement to create Primary Key :
ALTER TABLE Products
ADD CONSTRAINT pk_products_pid PRIMARY KEY(ProductID)
GO

Alter Statement to Drop Primary key:

ALTER TABLE Products
DROP CONSTRAINT pk_products_pid;

GO



Foreign Key Constraints : Foreign Key is a field in database table that is Primary key in another table. It can accept multiple nulls, duplicate values.

Create Table Statement  to create Foreign Key :
  1. Column Level :

USE AdventureWorks2008
GO
CREATE TABLE ProductSales
(
SalesID INT CONSTRAINT pk_productSales_sid PRIMARY KEY,
ProductID INT CONSTRAINT fk_productSales_pid FOREIGN KEY REFERENCES Products(ProductID),
SalesPerson VARCHAR(25)
);

GO

  1. Table Level :

CREATE TABLE ProductSales
(
SalesID INT,
ProductID INT,
SalesPerson VARCHAR(25)
CONSTRAINT pk_productSales_sid PRIMARY KEY(SalesID),
CONSTRAINT fk_productSales_pid FOREIGN KEY(ProductID)REFERENCES Products(ProductID)
);
GO

Alter Table Statement to create Foreign Key :

ALTER TABLE ProductSales
ADD CONSTRAINT fk_productSales_pid FOREIGN KEY(ProductID)REFERENCES Products(ProductID)
GO

Alter Table Statement to Drop Foreign Key :

ALTER TABLE ProductSales
DROP CONSTRAINT fk_productSales_pid;
GO


UNIQUE Constraint : The UNIQUE constraint uniquely identifies each record in a database table. The UNIQUE and PRIMARY KEY constraints both provide a guarantee for uniqueness for a column or set of columns.
Note that you can have many UNIQUE constraints per table, but only one PRIMARY KEY constraint per table.

Create Table Statement  to create UNIQUE constraint:

CREATE TABLE Persons
(
P_Id int NOT NULL UNIQUE,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)

Alter Table Statement to create UNIQUE constraint:

ALTER TABLE Persons
ADD UNIQUE (P_Id)

To allow naming of a UNIQUE constraint, and for defining a UNIQUE constraint on multiple columns, use the following SQL syntax:

ALTER TABLE Persons
ADD CONSTRAINT uc_PersonID UNIQUE (P_Id,LastName)

Alter Table Statement to Drop UNIQUE constraint:

ALTER TABLE Persons

DROP CONSTRAINT uc_PersonID



NOT NULL Constraint : The NOT NULL constraint enforces a column to NOT accept NULL values. The NOT NULL constraint enforces a field to always contain a value. By default, a column can hold NULL.

Example Using NOT NULL Constraint :

Create table student(s_id int NOT NULL,Name varchar(60),age int);

The above query will declare that the s_id field of student table will not take NULL value.

An attempt to execute the following SQL statement,
INSERT INTO student (Name, age) VALUES ('Smith', 25);

will result in an error because this will lead to column "S_ID" being NULL, which violates the NOT NULL constraint on that column.

Following example demonstrates both the way to create NOT NULL constraints.
USE AdventureWorks
GO
-- NOT NULL Constraint when Table is created
CREATE TABLE ConstraintTable
(ID INT, ColSecond INT NOT NULL)
GO
-- NOT NULL Constraint after Table is created
ALTER TABLE ConstraintTable
ALTER COLUMN ID INT NOT NULL
GO
--Clean Up
DROP TABLE ConstraintTable

GO

CHECK Constraint : The CHECK constraint is used to limit the value range that can be placed in a column.

Default Constraint: Default constraint when created on some column will have the default data which is given in the constraint when no records or data is inserted in that column.

Create Table Statement to create Default Constraint :
  1. Column Level

USE AdventureWorks2008
GO
CREATE TABLE Customer
(
CustomerID INT CONSTRAINT pk_customer_cid PRIMARY KEY,
CustomerName VARCHAR(30),
CustomerAddress VARCHAR(50) CONSTRAINT df_customer_Add DEFAULT 'UNKNOWN'
);
GO

  1. Table Level : Not applicable for Default Constraint

Alter Table Statement to Add Default Constraint :

ALTER TABLE Customer
ADD CONSTRAINT df_customer_Add DEFAULT 'UNKNOWN' FOR CustomerAddress
GO

Alter Table to Drop Default Constraint :

ALTER TABLE Customer
DROP CONSTRAINT df_customer_Add
GO


Example:

CREATE TABLE Student (Student_ID integer Unique, Last_Name varchar (30), First_Name varchar (30),
Score Integer DEFAULT 80);

and execute the following SQL statement,
INSERT INTO Student (Student_ID, Last_Name, First_Name) VALUES (10, 'Johnson', 'Rick');

Output :
The table will look like the following:

Student_ID         Last_Name         First_Name        Score

10                       Johnson                 Rick                         80

SQL Server Cursor Functions

Cursor : A cursor allows looping through a record set and performing a certain operation on each record within the set. SQL Server supports three functions that can help you while working with cursors: @@FETCH_STATUS, @@CURSOR_ROWS and CURSOR_STATUS.

A cursor life cycle can be described as follows:


  • Cursor is declared using the DECLARE CURSOR statement. This statement creates a cursor within SQL Server memory
  • Cursor is activated using OPEN CURSOR statement. At this point you can populate the cursor with a record set.
  • Data is retrieved from the cursor using the FETCH keyword.
  • A WHILE loop is executed within the cursor to perform some operation with the rows in the cursor with the condition that the FETCH command is successful.
  • Cursor is deactivated using CLOSE CURSOR statement. At this point you can't populate the cursor with additional rows. Nor can you work with rows within the cursor. However, you can re-open the cursor with OPEN CURSOR statement and perform additional work with the cursor.
  • The cursor is destroyed using DEALLOCATE CURSOR statement. Once the cursor is de-allocated it cannot be reopened.
@@FETCH : The most commonly used cursor function is @@FETCH_STATUS. This function determines whether FETCH keyword has successfully retrieved a row from the current cursor.

@@FETCH_STATUS can take one of the three values:

@@FETCH_STATUS value           Meaning

0
Successful fetch of a row within a cursor
-1
Fetch has failed. This could mean that the cursor has reached the beginning (or end) of the record set. This could also mean that we attempted retrieving a record that does not exist. For instance, if you attempt to grab 51st record within a cursor that has 50 records fetch status will be 1.
-2
The fetched row is missing. This means the record you're trying to FETCH has been deleted or its key has been updated since you have opened the cursor.

For example, the following cursor is populated with the top 5 customer names. While the cursor fetches rows successfully the @@FETCH_STATUS is 0. Once we get to the end of the result set @@FETCH_STATUS becomes -1:

DECLARE @customer_full_name VARCHAR(85)
DECLARE customer_cursor CURSOR FOR  SELECT TOP 5 FirstName + ' ' + MiddleName + ' ' + LastName FROM dimCustomer 
OPEN customer_cursor 
FETCH NEXT FROM customer_cursor INTO @customer_full_name
WHILE @@FETCH_STATUS =
BEGIN   -- typically you'd do some row-based operation here 
FETCH NEXT FROM customer_cursor INTO @customer_full_name 
SELECT @@FETCH_STATUS AS fetch_status 
END 
CLOSE customer_cursor 
DEALLOCATE customer_cursor

Results:
fetch_status 
0
fetch_status 
0
fetch_status 
0
fetch_status 
0
fetch_status 
-1


@@CURSOR_ROWS:

@@CURSOR_ROWS function returns the number of rows in the cursor which was opened last on the current connection. This means that if you have 3 cursors open @@CURSOR_ROWS will return the number of rows in the 3rd cursor. @@CURSOR_ROWS can take the following values:

@@CURSOR_ROWS value          Meaning
-m          Cursor is being populated asynchronously. "M" is the value of records in the record set.
-1            The cursor is DYNAMIC; that means, it reflects the changes to the data within the cursor. Therefore the number of rows can change due to addition or deletion of rows in the underlying tables. DYNAMIC cursors always return 1 as value of @@CURSOR_ROWS.
0              This can mean one of the following:

               Cursor has not been opened
               Cursor has no rows
               Cursor has been closed
N             Number of rows in the cursor record set. N is reported after the cursor has been fully populated
The following example shows you how @@CURSOR_ROWS value changes during the lifetime of the cursor:

DECLARE  @last_name  VARCHAR(20),

        @first_name VARCHAR(20)

DECLARE MY_CURSOR CURSOR  FOR
SELECT TOP 3 LASTNAME,

            FIRSTNAME

FROM   DIMCUSTOMER
SELECT 'cursor has ' + CAST(@@CURSOR_ROWS AS VARCHAR) + ' rows'
OPEN MY_CURSOR
FETCH NEXT FROM MY_CURSOR
INTO @last_name,

    @first_name

SELECT 'cursor has ' + CAST(@@CURSOR_ROWS AS VARCHAR) + ' rows'
WHILE @@FETCH_STATUS = 0

 BEGIN-- typically you'd do some row-based operation here 
   FETCH NEXT FROM MY_CURSOR
   INTO @last_name,
        @first_name
 END

CLOSE MY_CURSOR
SELECT 'cursor has ' + CAST(@@CURSOR_ROWS AS VARCHAR) + ' rows'
DEALLOCATE MY_CURSOR
Results:
cursor has 0 rows 
cursor has 3 rows 
cursor has 0 rows
If the same cursor is executed with DYNAMIC keyword against the entire DimCustomer table within Adventure Works database the results would show "cursor has -1 rows" while the cursor was being searched.

CURSOR_STATUS:

The CURSOR_STATUS function can be used effectively within a stored procedure that calls another stored procedure, which returns an output parameter of CURSOR data type. This function can be used with local or global cursors and determines whether or not the stored procedure has returned a cursor with a result set. The syntax is:

CURSOR_STATUS( 'local' or 'global', cursor name)
or

CURSOR_STATUS ('variable', cursor variable name)

LOCAL or GLOBAL keywords allow you to specify the cursor scope; VARIABLE keyword specifies that CURSOR_STATUS function should examine a cursor variable.


In order to use the CURSOR data type as an output parameter, you must specify VARYING keyword along with OUTPUT within the CREATE PROCEDURE statement.

SQL Server CAST() and CONVERT() Functions

The CAST and convert functions provide similar functionality. They are used to convert a value from one data type to another. So let's take a look at a practical example. The example is developed in SQL Server 2008 using the SQL Server Management Studio.

CAST () Function: The Cast() function is used to convert a data type variable or data from one data type to another data type. The Cast() function provides a data type to a dynamic parameter (?) or a NULL value.

Syntax: CAST ( [Expression] AS Datatype)

The data type to which you are casting an expression is the target type. The data type of the expression from which you are casting is the source type.

Example :
DECLARE @A varchar(2)
DECLARE @B varchar(2)
DECLARE @C varchar(2)
set @A=50
set @B=15
set @C=35
Select CAST(@A as int) + CAST(@B as int) +CAST (@C as int) as Result

Output: 100

Example :
DECLARE @Z char(30)
SELECT @Z=current_timestamp
select CAST (@Z as date) as result

Output: 2015-03-30


convert () Function: When you convert expressions from one type to another, in many cases there will be a need within a stored procedure or other routine to convert data from a datetime type to a varchar type. The Convert function is used for such things. The CONVERT() function can be used to display date/time data in various formats.
Syntax :
CONVERT(data_type(length), expression, style)

Style - style values for datetime or smalldatetime conversion to character data.  Add 100 to a style value to get a four-place year that includes the century (yyyy).

Example:
In this example we take a style value 108 which defines the following format:
hh:mm:ss
Now use the above style in the following query:
select convert(varchar(20),GETDATE(),108)
Output: 14:59:55
Example :
In this example we use the style value 107 which defines the following format:
Mon dd, yy
Now use that style in the following query:
select convert(varchar(20),GETDATE(),107)
Output:
Mar 30, 2015

Example:
In this example we see different style values which defines the following format.
SELECT CONVERT(VARCHAR(15),GETDATE(),6)
go
SELECT CONVERT(VARCHAR(16),GETDATE(),106)
go
SELECT CONVERT(VARCHAR(24),GETDATE(),113)

Output:
30 Mar 15
30 Mar 2015
30 Mar 2015 15:02:51:150

Thursday, 26 March 2015

SQL Server String Functions

String Functions :

LEFT Function : Transact-SQL supports retrieving portions of the string. For instance, to retrieve the first few characters from the left of the string you use the LEFT function.

The following example retrieves first four letters of employee last names in the AdventureWorksDW database:
SELECT LEFT(LastName, 4) AS FirstFourLettersOfLastName,  LastName FROM dbo.DimEmployee

Results:
FirstFourLettersOfLastName 
Gilb 
Brow 
Tamb

RIGHT Function: The RIGHT function retrieves the portion of the string counting from the right.
For example:
SELECT RIGHT(LastName, 4) AS FirstFourLettersOfLastName,  LastName as FullLastName FROM dbo.DimEmployee

Results:
LastFourLettersOfLastName FullLastName 
bert Gilbert 
rown Brown 
ello Tamburello



SUBSTRING Function: SUBSTRING function retrieves a portion of the string starting at the specified character and bringing back the number of characters specified.
 Syntax is:
SUBSTRING(string, starting_character_number, number_of_characters_to_return)

The following example will retrieve four characters from the employee last names, starting at the third character:
SELECT SUBSTRING(LastName, 3, 4) AS PortionOfLastName FROM DimEmployee
Results:
PortionOfLastName FullLastName 
lber Gilbert 
mbur Tamburello 
lter Walters

Notice that the SUBSTRING function finds the starting character by counting from the left. In other words, if we run SUBSTRING(LastName, 3, 4) against the last name of "Buchanan" we start on the 3rd character from the left - "c".


REVERSE Function: The REVERSE function gives you a mirror image of a given string.

The following example returns the mirror image of employee last names:
SELECT  REVERSE(LastName) AS MirrorImage,  LastName AS FullLastName  FROM DimEmployee

Results:
MirrorImage FullLastName 
trebliG Gilbert 
nworB Brown 
ollerubmaT Tamburello 

sretlaW Walters

REPLACE Function: REPLACE function replaces some characters within a string with another set of characters.
Syntax is:
REPLACE(string expression, value to be replaced, replacing value)

For example, the following query replaces each occurrence of the word "payable" with "receivable":

SELECT AccountDescription,  REPLACE(AccountDescription, 'payable', 'receivable') AS DreamOn FROM dimAccount WHERE AccountDescription LIKE '%payable%'



STUFF Function: The STUFF function inserts a set of characters into a given string at a given position.

Syntax is:
STUFF(string to manipulate, starting position, length, characters to insert)
For example, the following query adds " town " string to every city in DimGeography table:
SELECT  STUFF(city, 5, 6, ' town ') AS Manipulated,  City  FROM dimGeography

Results:
Manipulated  City 
Rock town n   Rockhampton 
Town town     Townsville 
Clov town       Cloverdale 
Find town       Findon 
Pert town       Perth

You saw how to find the position of a specific character or number of characters using CHARINDEX. Now you can apply that knowledge and use STUFF function to replace characters based on their position.

The following example determines the position of 'ville' in the City column and then replaces it with 'town':
SELECT STUFF(city, CHARINDEX('ville', city), 6, ' town ') AS Manipulated,  City FROM dimGeography  WHERE city LIKE '%ville'

Results:

Manipulated City 
Campbells town  Campbellsville 
Mel town  Melville 
Cross town  Crossville 
Mary town  Maryville 

Nash town  Nashville



LEN Function : The LEN function finds the length of the character string. The function takes the string as a single argument.

For example, the following query shows the length of each city name:
SELECT  LEN(city) AS number_of_characters,  City  FROM dimGeography

Results:
Number_of_characters City 
10  Alexandria 
13  Coffs Harbour 
12  Darlinghurst 
8    Goulburn 
9    Lane Cove


Note: Use the DATALENGTH system function to determine the number of characters in a TEXT column.

REPLICATE Function : The REPLICATE function repeats a given string specified number of times.

Syntax is: REPLICATE(string, number of times).

For example, the following query prints the string '100' five times:

SELECT REPLICATE('100', 5)
Result:
100100100100100


SPACE Function : The SPACE function is an equivalent of using REPLICATE to repeat spaces. This function takes a single argument - number of spaces you want to print.

UPPER and LOWER Functions: UPPER and LOWER functions change the case of the query's output. Both functions accept a string expression as the only argument.

For example, the following query will return the US cities and corresponding states in mixed case:

SELECT UPPER(LEFT(City, 1)) +  LOWER(SUBSTRING(City, 2, (LEN(City) - 1))) + ',' + SPACE(2)
+ UPPER(LEFT(StateProvinceName, 1)) +  LOWER(SUBSTRING(StateProvinceName, 2,(LEN(StateProvinceName) - 1)))  AS CityAndState
FROM DimGeography  WHERE CountryRegionCode = 'us'

Results:
CityAndState 
Chandler,  Arizona 
Gilbert,  Arizona 
Mesa,  Arizona 
Phoenix,  Arizona 
Scottsdale,  Arizona


ASCII Function: ASCII function returns the ASCII code value of the leftmost character of a string. This function is commonly used for comparing characters without knowing whether they're in upper or lower case. Upper case and lower case letters translate into different ASCII values, as the following example shows:

SELECT ASCII('A') AS UpperCase, ASCII('a') AS LowerCase

Results:
UpperCase   LowerCase 
 ----------- 

65          97

UNICODE Function : UNICODE function works just like ASCII, except it accepts the Unicode character value as input. This could be useful if you're working with international character sets.

CHARINDEX and PATINDEX Function : Transact-SQL supports two functions for finding an occurrence of a particular character (or number of characters) within a string: CHARINDEX and PATINDEX. CHARINDEX finds the starting position of a single character or string within a given column (or variable). In addition, if you suspect that the value you are searching for might occur multiple times within a given string you can specify the character number at which you want to start searching.

Syntax of the function is:
CHARINDEX(search value, string, starting search location)

For example, you might wish to find a position of an apostrophe inside employee last names. The following query shows how this can be achieved using CHARINDEX function:

SELECT  CHARINDEX("'", LastName) AS ApostrophePosition,  LastName AS FullLastName FROM DimEmployee  WHERE lastname LIKE '%%'

Results:

ApostrophePosition FullLastName 
2 D'Hers 
2 D'sa

Perhaps a more interesting example is finding an occurrence of a string, as opposed to an occurrence of a character. For example, city names often end with "ville", as in Huntsville or Clarksville. The following query finds the starting position of "ville" within city names:

SELECT  CHARINDEX('ville', city) AS Position,  City    FROM dimGeography  WHERE city LIKE '%ville'

Results:
Position City 
5 Daleville 
10 Campbellsville 
4 Melville 
6 Crossville 
5 Maryville

The next example finds the occurrence of the value within a variable, starting search at the 20th character:
DECLARE @variable VARCHAR(255) 
SELECT @variable = 'this is a string. this is also a string' 
SELECT  CHARINDEX('string', @variable, 20) AS Position

Results:
Position 
34

PATINDEX function is very similar to CHARINDEX - It also finds the position of the first occurrence of a character or multiple characters.
The difference is that you have to append % wildcards to PATINDEX.
This function searches for a pattern. If you use a % wildcard with CHARINDEX you won't find anything, unless your data contains percent signs.
If you're searching for a pattern at the end of the string expression, then you only have to use the % wildcard at the beginning of the pattern to be found, as in PATINDEX ('%pattern_to_find', string).

The following query returns the same results as CHARINDEX example:
SELECT  PATINDEX('%ville%', city) AS Position,  City FROM dimGeography  WHERE city LIKE '%ville%'

Use of PATINDEX function to display field value of table:
SELECT Address, PATINDEX('% %',Address) AS 'Index' FROM Customers

Output:
ContactName                             Index
Obere Str. 57                                6
Avda. de la Constitución 2222  6
Mataderos  2312                         10
120 Hanover Sq.                          4
Berguvsvägen  8                          13
Forsterstr. 57                               12

Use of PATINDEX function in where clause:
SELECT ContactName, Address FROM Customers
WHERE  PATINDEX('%8%',Address) > 0

Output:
ContactName            Address
Christina Berglund     Berguvsvägen  8
Diego Roel                C/ Moralzarzal, 86
Martine Rancé           184, chaussée de Tournai
Carlos Hernández      Carrera 22 con Ave. Carlos Soublette #8-35
Patricia McKenna      8 Johnstown Road
Jaime Yorres             87 Polk St. Suite 5


Above example displays all customers containing character '8' in addresss from customers table.


CHAR Function : The CHAR function does the opposite of ASCII - it returns an alphanumeric equivalent of an ASCII code. CHAR function accepts a single argument - a number between 0 and 255.

Syntax : CHAR ( integer_expression )

Examples of CHAR Function :

Use of CHAR function in select clause
SELECT CHAR(83)
Output:
S


Above example displays the use of CHAR function to display character based on ascii value.

STR Function: STR function is used to convert numeric value to character.

Syntax of STR Function :

STR ( float_expression [ ,length [ ,decimal ] ] )

float_expression is an expression of float data type with a decimal point.

length is total length including decimal point, sign, digits, and spaces. The default is 10. If you specify negative value then it returns NULL. It should be greater than or equal to the part of the number before the decimal point plus it's sign. If it is not so then it returns ** .

decimal is the number of places after decimal point. If you specify negative value then it returns NULL.

Return type of STR function is char.

Examples of STR function :

Example 1 : Use of STR function in select clause

SELECT STR(137.45,7,3)
Output:
137.450

Above example can displays 6 digits and a decimal point as seventh character. Fractional part of the number is rounded to three decimal places.



Example 2 : Converting negative number to character type using STR function

SELECT STR(-137.45,6,1)
Output:
-137.4


Above example displays 4 digits, 5th character as negative sign and 6th character as decimal point. Fractional part of the number is rounded to one decimal place.

LTRIM : LTRIM function returns the string by removing all the blank spaces at left side. It also takes 1 argument as string value.

Example:
select LTRIM('ASP    ')
Result: ASP-----
Blanks at the right side not removed.

RTRIM : RTRIM function returns the string by removing all the blank spaces at right side. It also takes 1 argument as string value.

Example:
select RTRIM('  ASP')
Result: -----ASP

Blanks at the left side not removed.