Thursday, May 29, 2008

Import Data from excel file to MSSQL database

Steps to import data from excel to the database:

Step 1: Go to Sql Server Enterprise Manager > Right click on local database server > All Tasks > Import Data



Step 2: A screen appears like below. Click Next



Step 3: Select Microsoft Excel option in Data Source, Browse and select the file and clilck Next



Step 4: Select the destination database name and click Next



Step 5: Select the database using check box which is provided and click Next.
Note: This process will automatically create a new table if the table does not exists.



Step 6: A screen appears like below. Click Next.



Step 7: Check Run immediately (default). Click Next.



Step 8: An alert is given after succesfully copying the data. Click OK.



Step 9: Click Done



Step 10: Click Finish


Tags: Import Data from excel file to MSSQL database, Excel Data to Sql server database, Export Data from sql server to excel file

Tuesday, May 20, 2008

Important SQL Queries, Important Database Queries

To find the nth row of a table
In oracle:
Select * from emp where rowid = (select max(rowid) from emp where rownum <= 4)

In Sql Server 2005:
Select * from emp where rowid = (select max(rowid) from emp where row_number() <= 4)

To find duplicate rows
Select * from emp where rowid in (select max(rowid) from emp group by empno, ename, mgr, job, hiredate, comm, deptno, sal)

To delete duplicate rows
Delete emp where rowid in (select max(rowid) from emp group by empno,ename,mgr,job,hiredate,sal,comm,deptno)

To find the count of duplicate rows
Select ename, count(*) from emp group by ename having count(*) >= 1

To display alternative rows in a table

In oracle:
select * from emp where (rowid,0) in (select rowid,mod(rownum,2) from emp)

Getting employee details of each department who is drawing maximum sal
select * from emp where (deptno,sal) in ( select deptno,max(sal) from emp group by deptno)

To get number of employees in each department, in which department is having more than 2500 employees
Select deptno,count(*) from emp group by deptno having count(*) >2500

To find nth maximum sal

In oracle:
Select * from emp where sal in (select max(sal) from (select * from emp order by sal) where rownum <= 5)


If you have to give a flat hike to your EMPloyee using the Following CriteriaSalary b/w 2000 and 3000 then Hike is 200Salary b/w 3000 and 4000 then Hike is 300 Salary b/w 4000 and 5000 then Hike is 400 in EMPLOYEE Table
Update EMPLOYEE Set Salary =

Case when Salary between 2000 and 3000 then

Salary = Salary+200

Case when Salary between 3000 and 4000 then

Salary = Salary+300

Case when Salary between 3000 and 4000 then

Salary = Salary+300

End


Tags: Important SQL Queries, Important Database Queries, Most Common SQL Queries

Monday, May 5, 2008

Database Triggers, Types of Triggers, Syntax of Triggers

Triggers are special types of Stored Procedures that are defined to execute automatically in place of or after data modifications.
They can be executed automatically on the INSERT, DELETE and UPDATE triggering actions.

Types of triggers:
1. INSTEAD OF:
A trigger that fires before the INSERT, UPDATE, or DELETE statement is conducted.
CREATE TRIGGER trigger name
ON table name
INSTEAD OF operation AS DML statements

2. AFTER:

AFTER triggers are executed after the action of the INSERT, UPDATE, or DELETE statement is performed.
CREATE TRIGGER trigger name ON table name AFTER operation AS DML statements

Note:
INSTEAD OF triggers may be defined on views where as AFTER cannot.

Tags: Database Triggers, Types of Triggers, Syntax of Triggers, Instead of trigger, After Trigger, Create Trigger

Stored Procedure| Database Stored Procedures| SQL Stored Procedures

A stored procedure is a set of SQL statements that can be stored in the server.

Benefits of Stored Procedures
1. Precompiled execution. SQL Server compiles each stored procedure once and then reutilizes the execution plan. This results in tremendous performance boosts when stored procedures are called repeatedly.

2. Reduced client/server traffic. If network bandwidth is a concern in your environment, you'll be happy to learn that stored procedures can reduce long SQL queries to a single line that is transmitted over the wire.

3. Efficient reuse of code and programming abstraction. Stored procedures can be used by multiple users and client programs. If you utilize them in a planned manner, you'll find the development cycle takes less time.

4. Enhanced security controls. You can grant users permission to execute a stored procedure independently of underlying table permissions.

Syntax:
CREATE PROCEDURE [procedure name] (@parameter1 type, @parameter2 type) AS
Sql statements………
BEGIN
END
…………….
GO

To declare variables:
DECLARE
Eg: DECLARE @temp int

To assign values:
SET
Eg: SET @temp = 0

To return a value:
CREATE PROCEDURE [proc name] (@p1 type, @p2 type output) AS
……
GO
Eg: Create Procedure GetAuthorsByLastName1 (@au_lname varchar(40), @RowCount int output) as select * from authors where au_lname like @au_lname; /* @@ROWCOUNT returns the number of rows that are affected by the last statement. */
select @RowCount=@@ROWCOUNT

Error Handling:
@@Error is used.

Include the SET NOCOUNT ON statement into your stored procedures to stop the message indicating the number of rows affected by a Transact-SQL statement.This can reduce network traffic, because your client will not receive the message indicating the number of rows affected by a Transact-SQL statement.

To Execute in query analyzer:
Exec [procedure name] [parameters]

To call from ASP page:
Rs.Open "exec [procedure name] [parameters]", conn

To write comments:
/* */

Tags: Stored Procedure, Database Stored Procedures, SQL Stored Procedures, Stored Procedure Syntax, Call a stored procedure from asp page, Execute a stored procedure, Error Handling in stored procedures

Database Indexing, Types of Index, Indexes

A database index is a copy of part of a table that is used to speed up data retrieval in a database.Indexes can be created using one or more columns, providing the basis for both rapid random lookups and efficient ordering of access to records.

Types of Index:
Clustered Index
Non-Clustered Index

Clustered Index:
A clustered index is a special type of index that reorders the way
records in the table are physically stored. Therefore table can have only one clustered index. The leaf nodes of a clustered index contain the data pages.
A clustered index stores data similar to a phone directory where all people with the same last name are grouped together. SQL Server will quickly search a table with a clustered index while the index itself determines the sequence in which rows are stored in a table. Clustered indexes are useful for columns searched frequently for ranges of values, or are accessed in sorted order.

CREATE UNIQUE CLUSTERED INDEX DummyTable2_EmpIndexON DummyTable2 (EmpID)GO

Non-Clustered Index:
A non-clustered index is a special type of index in which the logical order of the index does not match the physical stored order of the rows on disk. The leaf node of a non-clustered index does not consist of the data pages. Instead, the leaf nodes contain index rows.
A non-clustered index stores data comparable to the index of a text book. The index is created in a different location than the actual data. The structure creates an index with a pointer that points to the actual location of the data. Non-clustered indexes should be created on columns where the selectivity of query ranges from highly selective to unique. These indexes are useful when providing multiple ways to search data is desired.

CREATE UNIQUE NONCLUSTERED INDEX DummyTable1_empidON DummyTable1 (empid)GO

Tags: index, indexes, indexing, Database Indexing, Types of Index, Clustured Index, Non-Clustered Index, Syntax of Index, Clustured index syntax, Non clustured index syntax

Database Views| MSSQL Views| SQL Server Views| Syntax of Database Views| Types of Views

A view may be thought of as a virtual table, that is, a table that does not really exist in its own right but is instead derived from one or more underlying base table. In other words, there is no stored file that direct represents the view instead a definition of view is stored in data dictionary.
Growth and restructuring of base tables is not reflected in views. Thus the view can insulate users from the effects of restructuring and growth in the database. Hence accounts for logical data independence.

Syntax
CREATE VIEW [<> . ] view_name [ ( column [ ,...n ] ) ] [ WITH <> [ ,...n ] ] AS select_statement [ WITH CHECK OPTION ]
<> ::= { ENCRYPTION SCHEMABINDING VIEW_METADATA }
Note: Column is for statements, which contain aggregate functions
Encryption: Code View is encrypted by using this.
Schemabinding: The view is binded with the underlying table structure. Suppose you drop a column of the base table, normally the view gives an error that there is no such column name But if you specify With Schemabinding, then we will not be able to drop the column as it is being accessed by other objects.
View_MetaData: Returns the meta data information about the view.
Check Option: Suppose we create a view with a query, which has where condition. For this view, if the user tries to insert the data that does not match the query then its of no use as that is not shown in the result. So that means, we should give access only to insert records which meets the query criteria. Hence WITH CHECK OPTION is used. The result would be an error for the situation above.
A CREATE VIEW statement cannot:
Include ORDER BY clause, unless there is also a TOP clause (remember that a view is nothing else but a virtual table, why would we want to order it?)
Include the INTO keyword.
Include COMPUTE or COMPUTE BY clauses.
Reference a temporary table or a table variable.
Select statement can use multiple SELECT statements separated by UNION or UNION ALL.
Restrictions for updating data:
A view cannot modify more than one table. So if a view is based on two or more tables, and you try to run a DELETE statement, it will fail. If you run an UPDATE or INSERT statement, all columns referenced in the statement must belong to the same table.
It’s not possible to update, insert or delete data in a view with a DISTINCT clause.
You cannot update, insert or delete data in a view that is using GROUP BY.
It’s not possible to update, insert or delete data in a view that contains calculated columns.

Types:
Indexed Views: Indexed views work best for queries that aggregate or compute columns in the table. The disadvantage of indexed views is that it will slow down a query that updates data in the underlying tables.
Partitioned Views: When you need to write a join query with tables that are in different databases, then we use partitioned views.

Tags: Database Views, SQL Views, MSSQL Views, SQL Server Views, Syntax of Database Views, Types of Views, Types of database views

Database Joins| SQL Joins| Types of database Joins

Join actually puts data from two or more tables into a single result set.

Types:
Inner join or Equi join
Outer Join
Left outer Join
Right Outer Join
Full Outer Join
Cross Join
Self Join

Inner Join: An inner join returns all rows that result in a match.
Example: SELECT Employees.Name, Orders.ProductFROM EmployeesINNER JOIN OrdersON Employees.Employee_ID=Orders.Employee_ID

Left Outer Join: A Left join returns all rows of the left of the conditional even if there is no right column to match.
Example:SELECT Employees.Name, Orders.ProductFROM EmployeesLEFT JOIN OrdersON Employees.Employee_ID=Orders.Employee_ID

Right Outer Join: A right join will display rows on the right side of the conditional that may or may not have a match.
Example:SELECT Employees.Name, Orders.ProductFROM EmployeesRIGHT JOIN OrdersON Employees.Employee_ID=Orders.Employee_ID

Full Outer Join: Returns all the left, right (unmatched rows) and also matched rows.

Cross-Join: A cross join (or Cartesian Product join) will return a result table where each row from the first table is combined with each row from the second table. The number of rows in the result table is the product of the number of rows in each table.

Self-Join: A self-join is a query in which a table is joined (compared) to itself. Self-joins are used to compare values in a column with other values in the same column in the same table.
Example:
SELECT DISTINCT c1.ContactName, c1.Address, c1.City, c1.Region
FROM Customers AS c1, Customers AS c2
WHERE c1.Region = c2.Region
AND c1.ContactName <> c2.ContactName
ORDER BY c1.Region, c1.ContactName;

Tags: Database Joins, Sql joins,
Inner join, Equi join, Outer Join, Left outer Join, Right Outer Join, Full Outer Join, Cross Join, Self Join, Types of Database Joins

Database Normalization| SQL Normalization

Normalization is the process of efficiently organizing data in a database.
Goals: eliminating redundant data (for example, storing the same data in more than one table) ensuring data dependencies make sense (only storing related data in a table)
Levels: 1 NF, 2NF, 3NF, BCNF (Boyce-Codd Normal Form), 4NF, 5 NF

1 NF: Eliminate duplicative columns from the same table. Create separate tables for each group of related data and identify each row with a unique column or set of columns (the primary key).



2 NF: Meet all the requirements of the first normal form. Remove subsets of data that apply to multiple rows of a table and place them in separate tables. Create relationships between these new tables and their predecessors through the use of foreign keys.

3 NF: Meet all the requirements of the second normal form. Remove columns that are not dependent upon the primary key. Eg: total, average etc which can be calculated in sql query


Boyce-Codd NF:
A relation is in Boyce-Codd Normal Form (BCNF) if every determinant is a candidate key.
OR
Key attribute should not depend on a non key attribute.
Determinant: A determinant in a database table is any attribute that you can use to determine the values assigned to other attribute(s) in the same row.
Examples: Consider a table with the attributes employee_id, first_name, last_name and date_of_birth. In this case, the field employee_id determines the remaining three fields. The name fields do not determine the employee_id because the firm may have more than one employee with the same first and/or last name. Similarly, the DOB field does not determine the employee_id or the name fields because more than one employee may share the same birthday.
Candidate Key: A candidate key is a combination of attributes that can be uniquely used to identify a database record. Each table may have one or more candidate keys. One of these candidate keys is selected as the table primary key.

4 NF:
Meet all the requirements of the third normal form and BCNF.
A relation is in 4NF if it has no more than one multi-valued or multiple dependency.Consider these entities: employees, skills, and languages. An employee can have several skills and know several languages. There are two relationships, one between employees and skills, and one between employees and languages. A table is not in fourth normal form if it represents both relationships. Instead, the relationships should be represented in two tables. If, however, the attributes are interdependent (that is, the employee applies certain languages only to certain skills), the table should not be split.A good strategy when designing a database is to arrange all data in tables that are in fourth normal form, and then to decide whether the results give you an acceptable level of performance. If they do not, you can rearrange the data in tables that are in third normal form, and then re assess performance.


5NF:
(join-projection normal form)JPNF
It should be in 4NF.
No multi valued dependency exists.