Index:is a data structure that increases the speed of data retrieval operations in a table at the cost of slower writes and increased storage space.
Index can be created using one or more columns of a database table.
Index may be defined as unique or non-unique. A unique index acts as a constraint on the table by preventing duplicate entries in the index and thus the backing table.
Clustered and non clustered IndexSQL server creates a clustered index on a primary key by default
Non Clustered Index:The physical order of the rows is not the same as the index order.Typically created on column used in JOIN, WHERE, and ORDER BY clauses.Good for tables whose values may be modified frequently.
Clustered Index:Clustering results in the row data being stored in order. Therefore, only one clustered index can be created on a given database table.
Clustered indexes can greatly increase overall speed of retrieval, but usually only where the data is accessed sequentially in the same or reverse order of the clustered index, or when a range of items is selected.
Clustered Table and Heap Table:A table that does not have a clustered index is referred to as a HEAP and a table that has a clustered index is referred to as a clustered table.
Limitaion of Index
Index fragmentation: is a process in which index pages split due to heavy insert, update, and delete operations on a table in a database. This results in wasted space as well as additional data pages to read to satisfy the queries.
Resoltuion:•DROP INDEX followed by CREATE INDEX
•CREATE INDEX…WITH DROP_EXISTING
•DBCC DBREINDEX
•DBCC INDEXDEFRAG
Example of creating a clustered index on a Table:CREATE TABLE [AppDbo].[UserType](
[UserType_GID] [dbo].[GID_Type] NOT NULL,
[UserTypeID] [dbo].[IntCode_Type] NOT NULL,
[Description] [dbo].[Desc_Type] NOT NULL,
CONSTRAINT [PK_UserType] PRIMARY KEY CLUSTERED
(
[UserType_GID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
SQL Server Multipart Names:All Transact-SQL references to the name of a database object can be a four-part name in the following form:
a.)server_name.[database_name].[schema_name].object_name
b.)database_name.[schema_name].object_name
c.)schema_name.object_name
d.)object_nameTo omit intermediate nodes, use periods to indicate these positions.
The following table shows the valid formats of object names.
Object reference format/Description:
server.database.schema.object/Four-part name.
server.database..object/Schema name is omitted.
server..schema.object/Database name is omitted.
server...object/Database and schema name are omitted.
database.schema.object/Server name is omitted.
tabase..object/Server and schema name are omitted.
schema.object/Server and database name are omitted.
object/Server,database,and schema name are omitted.
Server and Database Security:
A.)Server Security-
Server roles and login:
The first step in protecting your client’s data is determining which users need to view which data and then allowing access to only those users. For example, a payroll clerk probably views salary figures for everyone in your company while team managers have access to salaries for team members.
Accommodating a number of users could be a huge task if it weren’t for the Windows security model, which can easily accommodate many users with one role. A role defines what a user can and can’t do within a database, and multiple users can share the same role
B.)Database Security-Users, Roles and Schemas-
Schema-
In a relational db the schema is the container of
-the tables, the fields, relationships, views, indexes, packages, procedures, functions, queues, triggers, types, sequences, materialized views, synonyms, database links and other elements.
The permissions are set in schemas. eg dbo schema can be granted connect permissions, app can be granted other permissions.
Roles- Groups created in the db to easily manage the responsibilities of users. They have attributes of schemas owned and role members.
Users-The users of the database. This category also shows a list of schemas owned and the roles associated with the person.
Difference between user defined function and stored procedure
1.)UDF can be used in the SQL statements anywhere in the WHERE/HAVING/SELECT section where as Stored procedures cannot be.
2.)UDFs that return tables can be treated as another rowset. This can be used in JOINs with other tables.
3.)Inline UDF's can be though of as views that take parameters and can be used in JOINs and other Rowset operations.
Creating Scalar Function:
CREATE FUNCTION [App].[FunctionName]
(@Para1 datatype,
@Para2 datatype)
RETURNS bit
AS
BEGIN
DECLARE @para3 datatype
IF---
---
ELSE set @para3=1
RETURN (@para3)
END
Executing a function:
DECLARE @param int
SET @param = App.IsMarkedIncorrectly(123,1)
SELECT @param
Creating Table Function:
CREATE FUNCTION [App][FunctionName]
(@Para1 [AppDbo][tableName] READONLY]
RETURNS TABLE
AS
RETURN
(
SELECT *
FROM NAME
WHERE---)
PROCEDURE
Creating A Procedure
CREATE PROCEDURE [App].[CheckingISVType]
@ISVType nvarchar(50),
@Rows int OUTPUT
AS
BEGIN
SET NOCOUNT ON--no counting on msgs
DECLARE @ISVTypeOld nvarchar(50)
SET @ISVTypeOld = @ISVType
IF @ISVType='Mid-Market'
SET @ISVType='Yes'
ELSE SET @ISVType = NULL
SELECT count (*)
FROM AppDbo.Azure_FY11_DataForMappingNew
SET @Rows=@@ROWCOUNT
SELECT
@ISVTypeOld AS OldTitle,
@ISVType AS NewValue
END
Calling the Function
DECLARE @ISVType varchar(50), @Rows int
--SET @ISVType = (select ISVType from AppDbo.Azure_FY11_DataForMappingNew WHERE ISVType IS NOT NULL)
select top 1 @ISVType = ISVType from AppDbo.Azure_FY11_DataForMappingNew
EXEC App.CheckingISVType @ISVType, @Rows OUTPUT--'Mid-Market'
GO
CURSOR
A cursor make it possible to define a result set (a set of data rows) and perform complex logic on a row by row basis.
To use cursors in SQL procedures, you need to do the following:
1.Declare a cursor that defines a result set.
2.Open the cursor to establish the result set.
3.Fetch the data into local variables as needed from the cursor, one row at a time.
4.Close the cursor when done
To work with cursors you must use the following SQL statements:
•DECLARE CURSOR
•OPEN
•FETCH
•CLOSE
CREATE PROCEDURE sum_salaries(OUT sum INTEGER)
LANGUAGE SQL
BEGIN
DECLARE SQLSTATE CHAR(5) DEFAULT '00000';
DECLARE p_sum INTEGER;
DECLARE p_sal INTEGER;
DECLARE c CURSOR FOR SELECT SALARY FROM EMPLOYEE;
SET p_sum = 0;
OPEN c;
FETCH FROM c INTO p_sal;
WHILE(SQLSTATE = '00000') DO
SET p_sum = p_sum + p_sal;
FETCH FROM c INTO p_sal;
END WHILE;
CLOSE c;
SET sum = p_sum;
END%
@@FETCH_STATUS
0-The FETCH statement was successful.
1-The FETCH statement failed or the row was beyond the result set.
2-The row fetched is missing.
DECLARE Employee_Cursor CURSOR FOR
SELECT BusinessEntityID, JobTitle
FROM AdventureWorks2008R2.HumanResources.Employee;
OPEN Employee_Cursor;
FETCH NEXT FROM Employee_Cursor;
WHILE @@FETCH_STATUS = 0
BEGIN
FETCH NEXT FROM Employee_Cursor;
END;
CLOSE Employee_Cursor;
DEALLOCATE Employee_Cursor;
GO
another example
ALTER PROCEDURE [App].[CheckingISVType]
@ISVType nvarchar(50),
@Rows int OUTPUT
AS
BEGIN
SET NOCOUNT ON--no counting on msgs
DECLARE @ISVTypeOld nvarchar(50)
DECLARE Table_Cursor CURSOR FOR (SELECT ISVType FROM AppDbo.Azure_FY11_DataForMappingNew)
SELECT count (*)
FROM AppDbo.Azure_FY11_DataForMappingNew
SET @Rows=@@ROWCOUNT
OPEN Table_Cursor
FETCH NEXT FROM Table_Cursor INTO @ISVType
WHILE @@FETCH_STATUS=0
BEGIN
SET @ISVTypeOld = @ISVType
IF @ISVType='Mid-Market'
SET @ISVType='Yes'
ELSE SET @ISVType = NULL
SELECT
@ISVTypeOld ,
@ISVType
FETCH NEXT FROM Table_Cursor INTO @ISVType
END
CLOSE Table_Cursor
END
Cursors and How to Avoid Them
In order to avoid using cursors, the developer must first understand why it is important to do so. Cursors operate on one row at a time whereas SQL Server is optimized to perform set-based operations (those affecting all the rows in one operation). Therefore a set-based solution is usually significantly faster than a cursor solution. How much faster of course depends on many factors, the number of records, the complexity of the operation, the load on the server, etc. But in every case where I have ever been able to replace a cursor with a set-based solution, performance has improved significantly.
I also believe that even when the data set it small, it is usually worthwhile to learn to perform the task without a cursor, so that the methods to avoid the cursor are well-learned and available when you need to affect a large data set. This is particularly true for the developer who has not yet learned to think in set-based terms as his or her first choice.
USER DEFINED DATA TYPES
TABLE
CREATE TYPE [AppDbo].[TableMappingData] AS TABLE(
[AggregatedSpinnakerID] [int] NULL,
[Reviewer] [nvarchar](200) NULL,
[IsNewCompany] [bit] NULL,
[Notes] [nvarchar](2000) NULL,
[WasCreatedAsNewCompanyInSpinnaker] [bit] NOT NULL,
[RecordActiveFlag] [bit] NOT NULL,
[SpinnakerID] [int] NULL,
[CompanyName] [nvarchar](150) NULL,
[Country] [nvarchar](100) NULL
)
Good topic, it will increase application performance.
ReplyDelete