About Me

My photo
Mumbai, Maharastra, India
He has more than 7.6 years of experience in the software development. He has spent most of the times in web/desktop application development. He has sound knowledge in various database concepts. You can reach him at viki.keshari@gmail.com https://www.linkedin.com/in/vikrammahapatra/ https://twitter.com/VikramMahapatra http://www.facebook.com/viki.keshari

Search This Blog

Showing posts with label ERROR Function. Show all posts
Showing posts with label ERROR Function. Show all posts

Wednesday, June 18, 2014

Creating series '22-47' '23-48' '24-49' in incremental order


Today I got a question in one of the SQL Forum, the problem statement was
“Hi, I have string like '21-46' i need output like '22-47' '23-48' '24-49'incremental order. etc...plz help me..

This reminds me the Pl/SQL session we use to have in our college days and my dbms faculty, pretty Snehal Mam…

So here he is the answer for the same.

create proc sp_NoSeries
@howLong int,
@strNo varchar(50)
as
begin
 try
     declare @cntr int
     declare @no1 int
     declare @no2 int
    declare @msg varchar(100)
   
     set @howLong = 6
     set @cntr = 0

     while (@cntr<@howLong)
     begin
           print @strNo
           set @no1=cast(substring(@strNo,0,charindex('-',@strNo)) as int) + 1
           set @no2=cast(substring(@strNo,charindex('-',@strNo)+1,len(@strNo)) as int) + 1
          
           set @strNo=cast(@no1 as varchar(10)) +'-' + cast(@no2 as varchar(10))
          
           set @cntr = @cntr +1
     end
 end try
 begin catch
     print 'Error occur that is '
     set @msg = (select error_message())
     print @msg
 end catch
go

Lets execute the procedure.

exec sp_NoSeries 6,'21-46'
21-46
22-47
23-48
24-49
25-50
26-51

exec sp_NoSeries 6,'21-df46'
21-df46
Error occur that is
Conversion failed when converting the varchar value 'df46' to data type int.

To be happy always, be a coder, to learn happiness, love coder! J
 

Post Reference: Vikram Aristocratic Elfin Share

Wednesday, January 1, 2014

SET XACT_ABORT, to rolls back current transaction on Run-Time Error


Specifies whether SQL Server automatically rolls back the current transaction when a Transact-SQL statement raises a run-time error.

To understand more on it we will do small practical, here we are creating two tables – table1 and table2 with primary key in first table as Parent Table and Foreign Key in second table as Child table.

create table table1
    (col1 int not null primary key);
create table table2
    (col1 int not null references table1(col1));
Go
Command(s) completed successfully.

Our table is ready, now lets insert some records in table 1, which has primary key on col1.

insert into table1 values (1);
insert into table1 values (3);
insert into table1 values (4);
insert into table1 values (6);
go

Now we are setting xact_abort to  off and inserting three records in child table table2 which is referenced by table1 primary key column.

set xact_abort off;
go
begin transaction;
insert into table2 values (1);
insert into table2 values (2); -- foreign key violation.
insert into table2 values (3);
commit transaction;
go

(1 row(s) affected)
Msg 547, Level 16, State 0, Line 3
The INSERT statement conflicted with the FOREIGN KEY constraint "FK__table2__col1__571DF1D5". The conflict occurred in database "Sparsh", table "dbo.table1", column 'col1'.
The statement has been terminated.
(1 row(s) affected)

select * from table2
col1
-----------
1
3

(2 row(s) affected)

In the above insertion the seocnd records which we were inserting was violating the Integrity constrain, since we were trying to insert value 2 which is not present in col1 of table1.
Eventhough the second insertion fails, it didn’t stop execution there and proceeds with the third row insertion and finally commited the 1 and 2 rows insertion implicitly. This is what happends due to xact_abort to  off.
   
Conclusion: SELECT shows only keys 1 and 3 added.  Key 2 insert failed and was rolled back, but XACT_ABORT was OFF and rest of transaction succeeded.

Now lets set xact_abort to  ON and tries to insert some good and bad records.

set xact_abort on;
go
Command(s) completed successfully.

begin transaction;
insert into table2 values (4);
insert into table2 values (5); -- foreign key violation.
insert into table2 values (6);
commit transaction;
go

(1 row(s) affected)
Msg 547, Level 16, State 0, Line 3
The INSERT statement conflicted with the FOREIGN KEY constraint "FK__table2__col1__571DF1D5". The conflict occurred in database "Sparsh", table "dbo.table1", column 'col1'.

select * from table2
col1
-----------
1
3

(2 row(s) affected)

Here from the output we can see none of the records gets inserted to the table even though the first and third records comply with the Integrity constrain. This is because, on the failure of the insertion of 2 records which was violating the integrity, the complete transaction rollback.

Conclusion: Key 5 insert error with XACT_ABORT ON caused  all of the second transaction to roll back.

Note: The alternative to this is TRY CATCH block

Take up a piece of code, blend it with ur logic, think dream n live it, let ur every part full of that logic, leave everything aside.. This is how Programmer lives their life. WILL U MARRY ME J  


Post Reference: Vikram Aristocratic Elfin Share

Monday, January 9, 2012

Function that will identify why your code fails. (USING TRY CATCH)


Function in TRY CATCH

Always try to put your code in the TRY block and you check for the errors in the CATCH block. SQL Server has a bunch of functions that will help you identify why your code failed, here is a list of the functions and what they return

ERROR_NUMBER()
returns the number of the error

ERROR_SEVERITY()
returns the severity of the error

ERROR_STATE()
returns the error state number

ERROR_PROCEDURE()
returns the name of the stored procedure or trigger where the error occurred, this will be NULL if you run an ad-hoc SQL statement

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

Let's run an example that generates a divide by zero error, in the catch we are just doing a simple select that calls the functions mentioned before to see what they return

begin try
      select 1/0 as 'DivisionResult'
end try
begin catch
      select
            error_number() as 'ErrorNumber',
            error_severity() as 'ErrorSeverity',
            error_state() as 'ErrorState',
            error_procedure() as 'ErrorProcedure',
            error_message() as 'ErrorMessage'
end catch

DivisionResult
--------------

(0 row(s) affected)

ErrorNumber ErrorSeverity ErrorState  ErrorProcedure  ErrorMessage
----------- ------------- ----------- --------------- -------------------------------
8134        16            1           NULL            Divide by zero error encountered.

(1 row(s) affected)

As you can see we got all that information back, that was pretty nice. Let's take it to the next step
Create the following table to store all the error information in

create table LogErrors (ErrorTime datetime,
                  ErrorNumber int,
                  ErrorSeverity int,
                  ErrorState int,
                  ErrorProc varchar(max),
                  ErrorLine int,
                  ErrorMessage varchar(max))

Command(s) completed successfully.

Create this stored procedure that will insert into the table we just created
create procedure proc_InsertError
AS
begin
      insert LogErrors
      SELECT GETDATE(),ERROR_NUMBER(),ERROR_SEVERITY(),ERROR_STATE(),ERROR_PROCEDURE(),ERROR_LINE(),ERROR_MESSAGE()
End

Command(s) completed successfully.

Run these 3 queries, they will generate 3 inserts into the LogErrors table

begin try
      SELECT 1/0
end try
begin catch
    EXEC proc_InsertError
end catch;
       
begin try
    SELECT convert(int,'a')
end try
begin catch
    EXEC proc_InsertError
end catch;
       
begin try
    SELECT convert(tinyint,300)
end try
begin catch
      EXEC proc_InsertError
end catch;

If you check now what is in the table, you will see 3 rows

select * from LogErrors
ErrorTime  ErrorNumber  ErrorSeverity ErrorState  ErrorProc   ErrorLine ErrorMessage
----------- ----------- ------------- ----------- ----------  --------  -----------
2012-01-09  8134        16            1           NULL         2        Divide by zero error encountered.
2012-01-09  245         16            1           NULL         9        Conversion failed when converting the varchar value 'a' to data type int.
2012-01-09  220         16            2           NULL         16       Arithmetic overflow error for data type tinyint, value = 300.

(3 row(s) affected)

Post Reference: Vikram Aristocratic Elfin Share