Wednesday, 15 April 2015

Cross and Outer Apply

Problem
SQL Server 2005 introduced the APPLY operator, which is very much like a join clause and which allows joining between two table expressions i.e. joining a left/outer table expression with a right/inner table expression. The difference between join and APPLY operator becomes evident when you have a table-valued expression on the right side and you want this table-valued expression to be evaluated for each row from the left table expression.
Solution:
 Cross Apply and Outer apply these two are allow us to join the table.
Cross Apply behaves like inner joins and Outter Apply behaves like Left outter join. But apply operator mostly used on table variables and DMV's (Dynamic Management Views and functions). Apply operator gives the most efficient result with table variables.
In inner join each check the condition each rows of both table and then it check the condition. Cross Apply returns those record which is present in the 2nd table as matched the condition. Whereas the OUTER APPLY operator returns all the rows from left table expression irrespective of its match with the right table expression.  For those rows for which there are no corresponding matches in right table expression, it contains NULL values in columns of right table expression.
Example and Test cases:
Creating two table                                      
1.    Employee 
2.    Department
With following structure
create table Dept (DeptId int identity constraint pk_DeptId Primary key, DeptName varchar(25) ,Location varchar(25) )


create table Emp (EmpId int identity Constraint pk_EmpId primary key,Ename varchar(30),DeptId int constraint fk_DeptId_Dept  references Dept(DeptId),Salary numeric(10))

I have inserted some data in both table but in Emp table I have insert some null data in DeptId column once I have firing command using  Cross apply it will gives the result as like inner join

SELECT * FROM Dept D
cross apply
(
      SELECT * FROM Emp E WHERE E.DeptId=D.DeptId
) Apply_demp


EmpId
Ename
DeptId
Salary
DeptId
DeptName
Location
2
Mandeep
1
25000
1
HR
Pune
3
Sandeep
2
25000
2
IT SW
Hyderabad
4
Amardeep
3
15000
3
Hardware
Chennai
6
Nitin
3
15000
3
Hardware
Chennai

But I don’t want to output like this means in this output some of the records are mismatch or not in result then it is not possible in such scenario so that we are using outer apply to display result for extracting output from Emp table in which DeptId is null
I am applying the outer apply then it will gives result as shown below
select * from Emp E
outer apply
(select * from Dept D where D.DeptId=E.DeptId) A

EmpId
Ename
DeptId
Salary
DeptId
DeptName
Location
1
Mangesh
NULL
15000
NULL
NULL
NULL
2
Mandeep
1
25000
1
HR
Pune
3
Sandeep
2
25000
2
IT SW
Hyderabad
4
Amardeep
3
15000
3
Hardware
Chennai
5
Akash
NULL
15000
NULL
NULL
NULL
6
Nitin
3
15000
3
Hardware
Chennai

The above scenario or our requirement we can get in this condition .
We can use table values function for implement this ,
Table Valued Function: This is the function which returns the result in the form of result set or table.
Firstly I have created following function
create function get_EmpDetails (@DeptId int)
returns table
as return(select *from Emp E where E.DeptId=@DeptId )

and applying outer and cross apply on it then the result may be as

select * from Emp E
outer apply get_EmpDetails(E.DeptId)
create function get_deptDetails(@DeptId int)
returns table
as
return (select * from Dept where DeptId=@DeptId)

Applying Cross Apply it will gives result as like on a table
select * from Emp E
outer apply get_EmpDetails(E.DeptId)
EmpId
Ename
DeptId
Salary
EmpId
Ename
DeptId
Salary
1
Mangesh
NULL
15000
NULL
NULL
NULL
NULL
2
Mandeep
1
25000
2
Mandeep
1
25000
3
Sandeep
2
25000
3
Sandeep
2
25000
4
Amardeep
3
15000
4
Amardeep
3
15000
4
Amardeep
3
15000
6
Nitin
3
15000
5
Akash
NULL
15000
NULL
NULL
NULL
NULL
6
Nitin
3
15000
4
Amardeep
3
15000
6
Nitin
3
15000
6
Nitin
3
15000

Error Handling in SQL sever


Error handling is mechanism through which we can avoid termination of the program as in programming language we can perform this operation in our stored procedure using TRY….CATCH  block
TRY CATCH:
Syntax:
BEGIN TRY
     { sql statement | statement block }
END TRY
BEGIN CATCH
     [ { sql statement | statement block } ]
END CATCH
[ ; ]

SQL Statement: It means T-SQL statements through which we can perform transaction on database
Statement Block: The group of SQL statements which are includes within the Block or Begin End block
Ø  A TRY…CATCH construct catches all execution errors that have a severity higher than 10 that do not close the database connection.
Retrieving the Information of Error:
In the scope of a CATCH block, the following system functions can be used to obtain information about the error that caused the CATCH block to be executed:
Ø  ERROR_NUMBER() returns the number of the error.
Ø  ERROR_STATE() returns the error state number.
Ø  ERROR_SEVERITY() returns the severity.
Ø  ERROR_PROCEDURE() returns the name of the stored procedure or trigger where the error occurred.
Ø  ERROR_LINE() returns the line number inside the routine that caused the error.
Ø  ERROR_MESSAGE() returns the complete text of the error message. The text includes the values supplied for any substitutable parameters, such as lengths, object names, or times.

Error_Number():
Returns the error number of the error that caused the CATCH block of a TRY…CATCH construct to be run.

Syntax:
Error_Number()
                        Return Type: Int        
Return Value: It returns the error number of the error message which is displaying if that is in Try…Catch block out of block it will returns NULL value
            Example:
            use [Sample Data]
begin try
select 1/0
end try
begin catch
select ERROR_NUMBER()
end catch

Error_Severity():
 Severity means the preference of the error and  in sql server the whose severity is greater than the 10 that situation database connection will not close means we can continue our task without any trouble

Severity 0 to 19
Error messages with a severity level of 10 are informational. Error messages with severity levels from 11 through 16 are generated by the user and can be corrected by the user. Severity levels from 17 and 18 are generated by resource or system errors; the user's session is not interrupted.
Using sp_addmessage we can add the user defined message to the severity form 19 to 25,but only the system admin can enter sysmessages
Level 10: Status Information, it gives the mistake user has done in the code.
Level 11 to 16: These Errors can correct by user
Level 17: These errors occurred only due to the Insufficient Resources (Like disk space is insufficient for the database).
Level 18: Nonfatal Internal Error, these messages says some internal software problem in it, T-SQL statements are executed connection and sql server maintains.
Level 19: SQL Server Error in Resource, these errors occurred due to the non-configurable internal limit has been exceeds.   
Severity 20 to 25:
Severity levels from 20 through 25 indicate system problems. These are fatal errors, which mean that the process is no longer running. The process freezes before it stops, records information about what occurred, and then terminates. The client connection to SQL Server closes, and depending on the problem, the client might not be able to reconnect.
Level 20: SQL Server Fatal Error in Current Process: These messages indicate that a statement has encountered a problem. Because the problem has affected only the current process, it is unlikely that the database itself has been damaged.
Level 21: SQL Server Fatal Error in Database (DBID) Processes: These messages indicate that you have encountered a problem that affects all processes in the current database; however, it is unlikely that the database itself has been damaged.
Level 22: SQL Server Fatal Error Table Integrity Suspect: These messages are comes when table and index damage due to some hardware and software problem.
Level 23: SQL Server Fatal Error: Database Integrity Suspect: These messages indicate that the integrity of the entire database is in question because of a hardware or software problem.
Level 24: Hardware Error: These messages indicate some type of media failure. The system administrator might have to reload the database. It might also be necessary to call your hardware vendor.
Example:
use [Sample Data]
begin try
select 1/0
end try
begin catch
select ERROR_SEVERITY()
end catch


Error State ():
Returns the state number of the error that caused the CATCH block of a TRY CATCH construct to be run.
The development team should know the exact location and reason of error trough which developer can resolve this problem easily, error state gives the clear picture of error and its information.
Syntax :
            Error_State()
Return type: int
Return Value: When called in a CATCH block, returns the state number of the error message that caused the CATCH block to be run. If we call it out of block it returns NULL value.
Example:
use [Sample Data]
begin try
select 1/0
end try
begin catch
select ERROR_STATE() as [Error State]
end catch

Error_Procedure:
This returns the procedure or trigger name in which the error has been occurred .
Syntax:
             Error_Procedure ()
Return Type
nvarchar(128)

      Return Value
      It gives the stored procedure or trigger name where error occurred, it gives the null if that procedure is not having error, it returns the null if we are call this function outside the try catch block
Note: In nested try catch block the Error_Procedure returns the stored procedure name within the scope of try catch block it executing.
Example:
                create procedure usp_ErrorProcedure
as
begin
begin try
select 1/0
end try
begin catch
select ERROR_NUMBER() as [Error Number],ERROR_SEVERITY() as [Error Severity],ERROR_STATE()  as [Error State],ERROR_PROCEDURE() as [Error Stored Procedure]
end catch
end

exec usp_ErrorProcedure

Error_Line()
            This returns the line number where error occurred which easily can find the cause for the error within the TRY CATCH block.
Syntax: Error_Line()
Return Type: int
Return Value: Returns the line number where error occurred, also return line number in routine if error occurred in the stored procedure, return null if it calls out of the TRY CATCH block



Example:
--Within the Query--
use [Sample Data]
begin try
select 1/2
select 5/10
select 1/'a'
end try
begin catch
select ERROR_LINE()
end catch

-- Within the stored procedure ---
alter procedure usp_ErrorProcedure
as
begin
begin try
select 1/0
end try
begin catch
select ERROR_NUMBER() as [Error Number],ERROR_SEVERITY() as [Error Severity],ERROR_STATE()  as [Error State],ERROR_PROCEDURE() as [Error Stored Procedure],ERROR_LINE() as[Error Line]
end catch
end

exec usp_ErrorProcedure



Error_Message():
Error message is the detailed description about the Error i.e. Text of error
Syntax: Error_Message()
Return Type: nvarchar(4000)
Return Value: It returns the text of error which gives the detailed description of error and values supplied for any substitutable parameters, such as lengths, object names, or times, returns NULL if called outside the scope of a CATCH block.

Note: ERROR_MESSAGE may be called anywhere within the scope of a CATCH block. If Block contains more than two statements having the error in that situation control preference is to first only.  
Consider the following example there are two statements having Errors in that situation on the first statement control goes to the Catch block .

Example:
use [Sample Data]
begin try
select 5/0
select 1/'a'
end try
begin catch
select ERROR_Message()
end catch
@@Error:
It returns the error number which will occur in the session previously.
Syntax: @@Error
Return Type: Interger
Note:
Returns an error number if the previous statement encountered an error. If the error was one of the errors in the sys.messages catalog view, then @@ERROR contains the value from the sys.messages.message_id column for that error. You can view the text associated with an @@ERROR error number in sys.messages.
@@Error value every time cleared and reset on every T-SQL Transaction.
Example: select @@ERROR




Custom User Defined Message:
We can define user defined Error message using sp_addmessage stored procedure, and which can be stored in sys.messages table 
Syntax
Sp_addmessage [@msgNumber=] msgId, [@severity=] severity, [@msgText=]’msg’
   [,[@language=] ’language’]
   [, [@ with_log =]{‘true’ | ’false’}]
   [,[@replace=] ‘replace’]

Arguments:
@msgNumber: is the message_id which is  by default null but we can gives Id from 50001 to 2,147,483,647, there is composite key on msgId and language so it gives error if repeating the data
 @severity :  Is the severity level of the error. severity is smallint with a default of NULL. Valid levels are from 1 through 25.

 @msgtext : is the message text which is in nvarchar(255) format  

@lang : Is the language for this message. language is sysname with a default of NULL. Because   multiple languages can be installed on the same server, language specifies the language in which each message is written. When language is omitted, the language is the default language for the session.
 @with_log:  Is whether the message is to be written to the Windows application log when it occurs. @with_log is varchar(5) with a default of FALSE. If TRUE, the error is always written to the Windows application log. If FALSE, the error is not always written to the Windows application log but can be written, depending on how the error was raised. Only members of the sysadmin server role can use this option.
 @replace: If specified as the string replace, an existing error message is overwritten with new message text and severity level. Replace is varchar(7) with a default of NULL. This option must be specified if msg_id already exists. If you replace a U.S. English message, the severity level is replaced for all messages in all other languages that have the same msg_id.
  Example:
exec sp_addmessage 50002,16,'no should be geeater than 0','us_english'
select * from Sys.messages where message_id=50002

sp_altermessage:
 This stored procedure is used for the altering the message of the user defined or system defined error
Syntax :
Sp_altermessage [ @message_id = ] message_number   ,[ @parameter = ]'write_to_log'
   ,[ @parameter_value = ]'value' 
 
Arguments:
@message_id: Is the error number of the message to alter from sys.messages. message_number is int with no default value.

@parameter (Write_to_log): it shows the message is written in the windows application log if we make with_log as true it writes the data in the window application and with_log is set to be false and message will not save in the windows application.

@parameter_value: Is used with @parameter to indicate that the error is to be written to the Microsoft Windows application log. value is varchar(5), with no default value. If true, the error is always written to the Windows application log. If false, the error is not always written to the Windows application log, but may be written depending upon how the error was raised. If value is specified, write_to_log for @parameter must also be specified.

Return value:
0 if Success
1 if Failure

Example:
exec sp_altermessage 50002, 'WITH_LOG', 'true';





sp_dropmessage:
Drops a specified user-defined error message from an instance of the SQL Server Database Engine. User-defined messages can be viewed using the sys.messages catalog view.

Syntax:
Sp_dropmessage [ @msgnum = ] message_number 
    [ , [ @lang = ] 'language' ]

Arguments:
@msgnum : It takes the message id which we want to delete or drop it
@lang: it asks for the language type like English, German etc. which that message having

Example:
exec sp_dropmessage 50002,'us_english'


Throw:
Raises an exception and transfers execution to a CATCH block of a TRY…CATCH construct in SQL Server 2012.
Syntax:
Throw [{error_number|@local_variable},
{message|@local_variable},
{state|@local_variable}
]
Argument:
error_number
Is a constant or variable that represents the exception. error_number is int and must be greater than or equal to 50000 and less than or equal to 2147483647.



message
Is an string or variable that describes the exception. message is nvarchar(2048).
state
Is a constant or variable between 0 and 255 that indicates the state to associate with the message. state is tinyint.
Notes:
Ø  The statement before the THROW statement must be followed by the semicolon (;) statement terminator.
Ø  If a TRY…CATCH construct is not available, the session is ended. The line number and procedure where the exception is raised are set. The severity is set to 16.
Ø  If the THROW statement is specified without parameters, it must appear inside a CATCH block. This causes the caught exception to be raised. Any error that occurs in a THROW statement causes the statement batch to be ended.
Difference between RaiseError and Throw
 RaiseError
Throw
If a msg_id is passed to RAISERROR, the ID must be defined in sys.messages.
The error_number parameter does not have to be defined in sys.messages.
The msg_str parameter can contain printf formatting styles.
The message parameter does not accept printf style formatting.
The severity parameter specifies the severity of the exception.
There is no severity parameter. The exception severity is always set to 16.

Example:
begin try
select 1/0
end try
begin catch
  throw
 end catch