Microsoft SQL Server

INDEX in SQL Server

An index is a physical structure containing pointers to the data. Indices are created in an existing table to locate rowsmore quickly and efficiently. It is possible to create an index on one or more columns of a table, and each index is given a name.

A clustered index is a special type of index that reorders the way records in the table are physically stored. Thereforetable can have only one clustered index. The leaf nodes of a clustered index contain the data pages.
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.

 //Clustered INDEX  
CREATE CLUSTERED INDEX index_name ON table_name(column_name);

//Non Clustered INDEX
CREATE NONCLUSTERED INDEX index_name ON table_name(column_name);

//DROP INDEX Syntax
DROP INDEX table_name.index_name
Microsoft SQL Server

USER-DEFINED FUNCTIONS in SQL Server

Scalar  Value Function
A Scalar-valued function in SQL Server 2012 is used to return a single value of any T-SQL data type.

 CREATE FUNCTION dbo.Calculate(@val1 int, @val2 int)  
RETURNS int
AS
BEGIN
DECLARE @val3 int;
SELECT @val3 = @val1 + @val2;
RETURN @val3;
END


Multi Table Value Function

1. Declare a table variable that is to be returned.
2. Must have a BEGIN/END block.
3. Inside the BEGIN/END block you need code that populates the table variable.
4. You return from the function.

 CREATE FUNCTION Util.MyMTVFunction (@Parameters INT)  
RETURNS @FunctionResultTableVariable TABLE (N INT)
AS
BEGIN
INSERT INTO @FunctionResultTableVariable (N)
SELECT column_name1,column_name2,...
FROM table_name
ORDER BY column_name ase|desc;
RETURN;
END
GO

In-line Table Value Function
1. Returns a select statement – there is no table variable to mess around with, no inserts, no code blocks.

 CREATE FUNCTION Util.MyITVFunction (@Parameters INT)  
RETURNS TABLE
AS
RETURN
SELECT column_name1,column_name2,...
FROM table_name
ORDER BY column_name ase|desc;
GO
Microsoft SQL Server

VIEW in SQL Server

A view can be thought of as a subset of a table. It can be used for retrieving data, as well as updating or deleting rows. Rows updated or deleted in the view are updated or deleted in the table the view was created with.

SQL CREATE VIEW Syntax

 CREATE VIEW view_name AS  
SELECT column_name(s)
FROM table_name
WHERE condition

Modify TABLE data through a VIEW

 UPDATE view_name  
SET column_name='Himen'
WHERE column_name= N'Patel' ;
Microsoft SQL Server

Difference between RETURN and OUTPUT in STORE PROCEDURE

RETURN variable can only return integers and that too, only one integer. It is not possible to return more than one value.

They are used to return SUCCESS and FAILURE.

OUTPUT variable, we can return more than one value and any datatype. They are used to return name, count, etc.