Labels

Showing posts with label SQLDeveloper. Show all posts
Showing posts with label SQLDeveloper. Show all posts

Wednesday, 28 June 2017

How to add new articles to Transactional Replication without Generating Snapshot of All Articles

Run the below commands on the Publication database





USE Distribution
GO

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

SELECT DISTINCT srv.srvname publication_server
 ,a.publisher_db
 ,p.publication publication_name
 ,a.article
 ,a.destination_object
 ,ss.srvname subscription_server
 ,s.subscriber_db
 ,da.name AS distribution_agent_job_name
FROM MSArticles a
INNER JOIN MSpublications p ON a.publication_id = p.publication_id
INNER JOIN MSsubscriptions s ON p.publication_id = s.publication_id
INNER JOIN master..sysservers ss ON s.subscriber_id = ss.srvid
INNER JOIN master..sysservers srv ON srv.srvid = p.publisher_id
INNER JOIN MSdistribution_agents da ON da.publisher_id = p.publisher_id
 AND da.subscriber_id = s.subscriber_id
ORDER BY 1 ,2 ,3









If the columns “immediate_sync” and “allow_anonymous” are having a value of 1(Enabled) for both of them, the Snapshot of all the articles will be generated.

As we do not want this behavior, we will change these values to 0(Disabled) for both the “immediate_sync” and “allow_anonymous” options.


We can disable these options by running below commands on Publication database.


Run the below commands on the Publication database


use <PublicationDB>
go
EXEC SP_CHANGEPUBLICATION @PUBLICATION = 'YOUR PUBLICATION NAME'

,@PROPERTY = 'ALLOW_ANONYMOUS' ,@VALUE = 'FALSE'

GO





EXEC SP_CHANGEPUBLICATION @PUBLICATION = 'YOUR PUBLICATION NAME'

,@PROPERTY = 'IMMEDIATE_SYNC' ,@VALUE = 'FALSE'

GO




Add article through GUI




use <PublicationDB>
go
EXEC SP_CHANGEPUBLICATION @PUBLICATION = 'YOUR PUBLICATION NAME'

,@PROPERTY = 'IMMEDIATE_SYNC' ,@VALUE = 'TRUE'
GO
EXEC SP_CHANGEPUBLICATION @PUBLICATION = 'YOUR PUBLICATION NAME'

,@PROPERTY = 'ALLOW_ANONYMOUS' ,@VALUE = TRUE



















Friday, 23 September 2016

SQL Server : Slow running query resons

                                                    Query Performing Slowly

1) Identify the SPID of the query from Sys.sysprocesses

2) Find any blockings exists or not and if it exists find the LEAD Blocker.

3) Identify how many connections are there, Benchmark if exceeds is an issue

4) CPU Utilization, Memory Utilization, System Memory Information and how much SQL Server is consuming. If AWE is enabled or not.

5) Any jobs are running both at OS level and SQL Server level.

6) Affinity Mask for Processor and IO should be checked.

7) Query observation, Coding standards have been followed or not. Commit issued at regular intervals in the code.

8) Table statistics are outdated. Need to update stats.

9) Indexes are created on correct columns are not. Verify the query and check the columns listed under WHERE condition and ensure that there are indexes created.

10) Even if indexes are created, they are fragmented or not.

11) Run server side trace to track what other activities are currently being rolled out to find the cause of the issue. If approved Profiler also can be used.

12) Network Latency between Client and the Server can cause performance issue.

13) MAXDOP feature can be utilized to improve the parallel execution of the query.

14) If clustered instance and Active-Active (N+1/N+M) Multiple Instance. If all nodes fail the last surviving node has all instances running on it causing performance issue.

15 )  Check disk space availability for that database and also for system databases.

16 ) Verify if any Application or Database specific jobs are running or not.

17 ) Network bandwidth to be verified and also Storage SAN bandwidth when accessing data. Contact Network/Storage team.

18) Identify top 10 long running queries and see if they are causing the performance lag.

19) Ask requester for the Query. Verify the Estimated Execution Plan of the Query.

20) Check if any Table Scans are present in the Plan. Table Scans are very expensive from resource perspective.

Also verify the Load on the system, Example average load is 2500 but we could see 10,000 connections.

Wednesday, 27 July 2016

ACID properties in SQL Server

ACID Properties is one of the most popular interview question. Moreover, I strongly believe that every software developer as well as database administrator should know the answer to this question. When you design any system or database, make sure you select the database which follows these properties as that will help you to develop better applications for your business needs.

A Transaction is a group of database commands that are treated as a single unit.A successful transaction must pass the "ACID" test i.e it should pass Atomic,Consistent,Isolation and Durability.

Atomic: Either Transaction completes or rolled back

All statements in the transaction either completed successfully or they were all rolled-back. The tasks that the set of operations represents is either accomplished or not but in any case not left half-done.

Consistent : Guarantees committed transaction state

Consistency guarantees that a transaction never leaves your database in a half-finished state.


Isolation : Transactions are independent

Isolation keeps transactions separated from each other until they’re finished.For this databases use locking mechanism to maintains transaction isolation.

Durability : Committed data never lost

Durability guarantees that the database will keep track of pending changes in such a way that the server can recover from an abnormal termination i.e system error or power failure.


Friday, 1 July 2016

Triggers in SQL Server

TRIGGERS

* It is also a SP but executed automatically when a DDL or DML command is executed.
* The statement, responsible for the invocation of a trigger is called triggering    statement.
* Triggering statements
                                                * CREATE, ALTER, DROP
                                                * INSERT, UPDATE, DELETE
                                                * Login event

* It is an extra instruction to db engine.
* S.P is executed manually but trigger is executed automatically.
* S.P can take parameters but trigger cannot parameter.

Advantages

* To implement complex business logic, which cannot be possible with the help of constraints?
* To implement automatic background process.
* To control the execution by the db engine.
* We can perform some extra task by the db engine along with the operators command.
* We can perform some alternate task when the command is issued by the operator.
* To audit the changes.
* To monitor the DDL commands.
* To restrict to perform some task on particular days or time or by a particular users.
* To provide high security for data.

Syn:
                CREATE TRIGGER <TRIGGERNAME>
                ON <tname>/<viewname>/database/Server
                FOR/INSTEAD OF commands
                as
                BEGIN
                                ---
                                ---
                END

Types of Triggers

                * For/After Triggers
                                * DML
                                * DDL      (introduced in SS2005)
                * Instead Of ,,
                * Logon Tiggers   (introduced in sp2)




1. For /After Triggers

                * First triggering st is executed then trigger is fired.
                * If we want to undo the changes made by trigger st then we have to  ROLLBACK.
                * To perform some extra task along with triggering statement.

                 Execution Plan
               
                                * Triggering statement is
                                                                * Parses     (compiling & syntax)
                                                                * Resolves   (Verifying cols, tables etc used in the query)
                                                                * Optimizes  (Generates execution plan)

                                * It prepares magic table(s)
                                * Triggering statement is executed.
                                * Trigger body is fired.

               
 Ex1: Trigger to prevent deletions on sunday on Accs_Ledger table.
               
CREATE TRIGGER DAY_TRG
ON accs_ledger
FOR DELETE
AS
BEGIN
                if datename(dw,getdate())='Sunday'
                Begin
                                rollback tran
                                Print 'Cannot delete on this day'
                End
END-- END OF TRIGGER

--step2: Testing trigger
* Change system date to Sunday.
* Run delete command
                delete from accs_ledger
* Trigger is fired and it throws error

Ex:                          Emp_Tbl
                               
                empid   ename  sal           deptno
                1              ---           9000       10

                Update emp_tbl set sal=9000 where empid=1
               
                When salary is updated we need to store the details in another table

                sal_updated
                                empid oldsal      date_updated

                When update command is executed in the background two tables are created.
                                                * deleted
                                                * inserted
               
                                Deleted                                                                                Inserted
empid   ename  sal           deptno                 empid   ename  sal           deptno
1              ---           8000       10                           1              ---           9000       10

                * These 2 tables are called as magic tables present in SQL Server.

                1) Deleted table
               
                i) It is created while working with delete or update commands.
                ii) It consists of deleted rows.
                iii) Its structure is similar to base table on which triggering statement is executed.

                2) inserted table
               
                i) Another magic table, created while working with insert or update commands.
                ii) It consists of new row.
                iii) Its structure is similar to base table.

               
Step-1 
create table sal_updated (empid int,oldsal money,date_updated datetime)
Step-2
create trigger sal_trg  on emps
for update
as
begin
                if update(sal)
                                insert sal_updated select empid,sal,getdate() from deleted
END --end of the trigger
               
Step3
update emps set sal=10000 where empid=1

select * from sal_updated

select * from emps
               



Ex: Create a trigger which prevents to insert more than 3 empls in 20 dept.

Step1
create trigger dept20_trg  on emps
for  insert,update
as
begin
                declare @dno int
                select @dno=deptno from inserted
                if @dno=20
                begin
                                if(select count(*) from emps where deptno=20)>3
                                rollback
                                raiserror('More than 3 empls are not allowed in 20 th dept',15,16)
                end
end
Step 2
insert emps(empid,sal,deptno) values(100,5000,20)
Ex:
Create a trigger which prevents insertion of rows with the salary >50000.
Step 1
create trigger sal_trg
on emps
for insert
as
begin
declare @sal money
select @sal=sal from inserted
if @sal >50000
begin
rollback
raiserror('salary greater than 50000 not accepted',12,16)
end
end

Step 2
insert emps(empid,sal) values(50,55000)
Ex: Create a trigger to prevent deletion of 10 dept empls whose sal<10000.
 create trigger dept10_trg on emps
for delete
as
begin
                declare @dno int , @sal money
select @dno=deptno from deleted
select @sal=sal from deleted
if @dno=10 and @sal<10000
begin
rollback
raiserror('dept10 employees with salless than 10000 cant be deleted',15,16)
end
end
Step2
delete from emps where empid=1
Ex:
                                Accs_ledger                                                                       deposits
                acno      ah_name             amt_bal               branch   acno amt            date_deposited
                1              ---           50000    Ampt     1              5000       ---

Create a trigger to update amt_bal of accs_ledger table when a  record is inserted into deposits table.

Step 1
create trigger deposits_trg
on deposits
for insert
as
set nocount on
begin
                declare @acno int,@amt money
                select @acno=acno from inserted
                select @amt=amt from inserted
                update accs_ledger set amt_bal=amt_bal+@amt where acno=@acno
                if @@rowcount=1
                                print 'Transaction Success'
                else
                                Print 'Transaction Failed'
end

Step 2

Insert deposits values(1,500,getdate())
Step 3

select * from accs_ledger
2. DDL Triggers
                * These triggers are fired when a DDL command is executed.
                * We can monitor DDL activities on database level or object level.
                * To provide security for database objects.
                * Complete event details we can capture by using "EVENTDATA()".
                * EVENTDATA() returns the details in XML format.

               
<EVENT_INSTANCE>
    <EventType>type</EventType>
    <PostTime>date-time</PostTime>
    <SPID>spid</SPID>
    <ServerName>name</ServerName>
    <LoginName>name</LoginName>
    <UserName>name</UserName>
    <DatabaseName>name</DatabaseName>
    <SchemaName>name</SchemaName>
    <ObjectName>name</ObjectName>
    <ObjectType>type</ObjectType>
    <TSQLCommand>command</TSQLCommand>
</EVENT_INSTANCE>

Ex: Create a trigger which prevents alter,drop on tables.
Step1
CREATE TRIGGER ddl_trg  ON DATABASE
FOR ALTER_TABLE,DROP_TABLE
AS
BEGIN
                ROLLBACK TRAN
                RAISERROR('You cannot drop or alter tables',15,16)
END
STEP2
drop table emps
Ex:  Create a trigger which stores the details when the user works with any ddl command.
Step3:  creating table to hold the ddl events.
USE Test;
GO
CREATE TABLE ddl_log (PostTime datetime, DB_User nvarchar(100), Event nvarchar(100),  TSQL nvarchar(2000));
GO
Step4:  creating trigger which inserts rows into ddl_log table.

CREATE TRIGGER log_trg
ON DATABASE
FOR DDL_DATABASE_LEVEL_EVENTS
AS
DECLARE @data XML
SET @data = EVENTDATA()
INSERT ddl_log
   (PostTime, DB_User, Event, TSQL)
   VALUES
   (GETDATE(),CONVERT(nvarchar(100), CURRENT_USER),
   @data.value('(/EVENT_INSTANCE/EventType)[1]', 'nvarchar(100)'),
   @data.value('(/EVENT_INSTANCE/TSQLCommand)[1]', 'nvarchar(2000)') ) ;
GO

Step3: Testing trigger

Test the trigger.
CREATE TABLE TestTable (a int)
DROP TABLE TestTable ;
GO
Step4: Viewing the above event details
SELECT * FROM ddl_log ;
GO
Step5: Dropping trigger
Drop the trigger.
DROP TRIGGER log_trg ON DATABASE
GO
Step 6: Dropping table ddl_log.
DROP TABLE ddl_log
GO
Ex: Displaying the event when create command is executed.
Step1: Creating trigger
USE Test
GO
CREATE TRIGGER safety  ON DATABASE
FOR CREATE_TABLE
AS
    PRINT 'CREATE TABLE Issued.'
    SELECT EVENTDATA().value
        ('(/EVENT_INSTANCE/TSQLCommand/CommandText)[1]','nvarchar(max)')
   RAISERROR ('New tables cannot be created in this database.', 16, 1)
   ROLLBACK
;
GO
Step2: Test the trigger.
CREATE TABLE NewTable (Column1 int);
GO
Step3: Drop the trigger.
DROP TRIGGER safety ON DATABASE
GO
3. INSTEAD OF Triggers
* To perform some alternate task when a command is issued by the operator.
* Here triggering statement is not executed only trigger body is fired.
* We can update complex views with these triggers.
   
Ex:- Create a trigger which prevents insert on emps table.

Step1

CREATE TRIGGER Emps_trg  ON EMPS
INSTEAD OF INSERT
AS
SET NOCOUNT ON
BEGIN
                RAISERROR('You cannot insert rows',14,17)
END
Step 2

INSERT Emps VALUES(10,'Kim',5000,10)

Step 3

SELECT * FROM Emps     -- Record is not inserted

Ex2: Create a trigger to update complex view, "emp_vw".

Step1

CREATE VIEW emp_vw
AS
SELECT empid,sal as M_sal, sal*12 as A_sal FROM emps
Step2

INSERT emp_vw VALUES(10,1000,12000)

Step3

CREATE TRIGGER INS_Trg
ON emp_vw
INSTEAD OF INSERT
AS
SET NOCOUNT ON
BEGIN
                INSERT emp(empid,sal) SELECT empid,M_sal FROM INSERTED
END

Step4

INSERT emp_vw VALUES(10,1000,12000)  -- inserted successfully.

Step5:

SELECT * FROM emps

Step6:

SELECT * FROM emp_vw

4. Logon Triggers

* These triggers were introduced in service pack2 on SQL Server 2005.
* Once the login is authenticated successfully then these triggers are fired.
* We can use these triggers to perform something like storing details  etc, when the user logon to server.
* There is no triggering statement.

Create a trigger which doesn't allow the user login_test to take more than 3 sessions.
Step1:   Creating login
USE master;
GO
CREATE LOGIN login_test WITH PASSWORD = 'hyd@123'
GO
Step2:   Granting permission
GRANT VIEW SERVER STATE TO login_test;
GO
Step3:   Creating trigger
CREATE TRIGGER connection_limit_trigger
ON ALL SERVER
WITH EXECUTE AS 'login_test'
FOR LOGON
AS
BEGIN
IF ORIGINAL_LOGIN()= 'login_test' AND
    (SELECT COUNT(*) FROM sys.dm_exec_sessions
            WHERE is_user_process = 1 AND
                original_login_name = 'login_test') > 3
    ROLLBACK;
END;

To view triggers present on table

sp_helptrigger <tname>
ex
sp_helptrigger emp

To Disable Or Enable Trigger

alter table <tname> disable/enable trigger <triggerName>

To drop trigger

drop trigger <triggerName>        -- For table level
drop trigger <triggerName> on database              -- For database level
drop trigger <triggerName> on all server              -- For server level

To view the trigger definition

sp_helptext <triggerName>


Monday, 30 May 2016

Stored Procedures in SQL Server


                                                                STORED PROCEDURES
                                                                                                                                               
* To implement business logic which should be executed in the database server we can use SPs.
* It is a program, present in compiled format.
* Max size of SP is 250 MB
* It can take value(s) from front end part with input parameter.
* Once the SP is executed we can take values back to front end part with output parameters.
* A SP can receive max 1024 parameters.
* The aim of SP is to move business logic closer to data.

Advantages

                * To move business logic closer to data.
                * To implement high performance i.e no need the logic to compile again and again
                * To reduce n/w traffic i.e no need to send business logic to server again and again.
                * Easy enhancements.
                * Re-usability.
                * Reduces task of administration.
                * Providing security.

Types of SPs

                * System Defined

                                Ex:          sp_help, sp_helptext, sp_rename

    * User Defined

                                * Created by the developer.
                                * T-SQL SPs.
                                * CLR SPs.

Steps to create SP

1. Creating SP
                create proc/procedure <SP_Name>
                (
                                parameters
                )
                as
                begin
                                ----
                                ----
                                ----
                end

2. Executing SP
                Exec <SP_Name> [parameter values]

WAP without parameters

CREATE PROCEDURE p1
AS
BEGIN
 PRINT 'SQL and Sai Technologies'
END


Execution:
                           EXEC p1

Ex:          Create procedure which returns sum of 2 integers

Step1:   Creating SP

               CREATE PROCEDURE sum_sp
         AS
        BEGIN
 DECLARE @a INT
  ,@b INT
  ,@sum INT

 SET @a = 10
 SET @b = 20
 SET @sum = @a + @b

 PRINT @sum
        END

Step 2:   Calling SP

             EXEC sum_sp

FAQ:- Diff between S.P and View?

                View                                                     Stored Procedure
                                                                               
1) It consists of only SELECT cmd.              1) It can have any commands.
2) It cannot take parameters.                          2) It can take parameters.
3) We can call the view with select                3) Execute statement
    statement.
4) It is a stored query.                                     4) It is a reusable code component.

Note:
                1) To view the s.p definition

                                sp_helptext <spname>
                Ex:
                                sp_helptext dept_Noe_sp

                2) S.P definition is stored in syscomments table hence we can view it as follows.
                select text from syscomments where id=object_id('dept_noe_sp')

Stored Procedure Lifecycle

1) At the time of creation its details are stored in
                                                Sysobjects
                                                Syscomments
                                                Sysdepends
Note:
                To find the objects used in a stored procedure
                select name as objectName,xtype as object_Type from sysobjects where id=(select depid from sysdepends where id=(select id       from sysobjects where name='dept_noe_sp'))

2) First time calling
                                                * Compiled
                                                * Execution plan is generated.
                                                * Compiled code with execution plan is stored in   procedure  cache.
                                                * Executed.

3) Next time calling
                                                * Executed.
Note:
                To view the details of cached batches
                DBCC PROCCACHE

Procedure Cache

The procedure cache is used to cache the compiled and executable plans to speed up the execution of the batches.
The entries in a procedure cache are at a batch level. The procedure cache includes the following entries:
                * Compiled plans
                * Execution plans
                * Algebraic tree
                * Extended procedures

Working with Parameters

* Input Parameters

                                * These are used to pass data to the stored procedure at the time of calling.
                                * These are default type of parameters.
                                * We can initialize value for input parameter.
                                syn:
                                                @pname type [INPUT[=value]]
                                Ex:
                                                1) @eno int
                                                2) @premium Money Input
                                                3) @salary Money=1000

Note: If we initialize input parameter it becomes optional parameter. i.e at the time of calling s.p no need to mention value for this  parameter.

Ex:- Create a stored procedure which takes 2 integers and displays sum.

CREATE PROCEDURE Sum_sp (
 @a INT
 ,@b INT
 )
AS
BEGIN
 DECLARE @c INT --declaring local variable

 SET @c = @a + @b

 PRINT @c
END --end of SP

--calling s.p

EXEC Sum_sp 10,20
or
EXEC Sum_sp @a = 50 ,@b = 40 --it allows to pass values in any order as well as provides  better clarity.

Using Optional Parameters

* If we initialize value to input parameter then it becomes optional parameter.
Ex:

Step 1

CREATE PROCEDURE EMP1_SP (@dno INT = NULL)
AS
BEGIN
 IF @dno IS NULL
  SELECT *
  FROM EMP
 ELSE
  SELECT *
  FROM emp
  WHERE deptno = @dno
END

Step2

EXEC EMP1_SP      -- calling s.p without passing value for @dno which takes null
EXEC EMP1_sp @dno = 10 -- calling s.p for a particular dept details.

Working with OUTPUT parameters

These parameters are used to return values from the subprogram i.e return values from subprogram to client application. Here we can explicitly specify OUT keyword.

Ex: A procedure with OUTPUT parameter

CREATE PROCEDURE proc4 (
 @x INT
 ,@y INT @z INT OUTPUT
 )
AS
BEGIN
 SET @x = @x + @y
END

Execution:

DECLARE @a INT

EXECUTE proc2 500
 ,250
 ,@a OUTPUT

PRINT @a
Ex 2:

Develop a SP which takes empno and returns the provident fund and Professional tax at 12% and 50% respectively on the salary?

CREATE procedue deductions (
 @empno INT
 ,@pf MONEY OUTPUT
 ,@pt MONEY OUTPUT
 )
AS
BEGIN
 DECLARE @sal MONEY

 SELECT @sal = sal
 FROM emp
 WHERE empno = @empno

 SET @pf = @sal * 0.12
 SET @pt = @sal * 0.05
END

Execution:

DECLARE @vdf MONEY
 ,@vpt MONEY

EXEC deductions 1005
 ,@vpf OUTPUT
 ,@vpt OUTPUT

PRINT @vpf
PRINT @vpt

Develop a stored procedure to transfer amount from one account to the other within the bank table?

CREATE PROCEDURE funds_transfer (
 @srid INT
 ,@destid INT
 ,@amt MONEY
 )
AS
BEGIN
 UPDATE bank
 SET bal = bal - @amt
 WHERE custid = @srid

 UPDATE bank
 SET bal = bal + @amt
 WHERE custid = @destid
END

Execution:

EXECUTE funds_transfer 101,102,500

Note:
In the above case if the srid or destid are not present in the table then it will deduct the amount from the other or add the amount to other. To avoid this we need to use transaction management
To manage the transaction we need to identify which statement is executed and whic one failed for this we use the function @@rowcount
@@rowcount returns nof rows effected by the last statement

Handling Errors in SP (or) Working with TRY Catch block:

                It is used to manage or handle run time errors. In SQL Server 200 and 2005 @@error is used to manage run time errors

TRY:
                It contains the instruction that might cause an exception.

CATCH:

                It execute only when run-time errors occurs.

                                FUNCTION                                                          DESCRIPTION

                ERROR_NUMBER()                                                          Returns the number of the error.
                ERROR_SERVITY()                                                           Returns the severity level.
                ERROR_STATE()                                                                Returns the error state number.
                ERROR_PROCEDURE()                                                   Returns the name of the SP 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 error message.  The text include the values  supplied for any substitutable parameters such as lengths,object names or times.

Note:
Servity levels are associated with the error. Range is b/n 0 and 25 , if it is >20 then client connection is terminated.

CREATE PROCEDURE div (
 @x INT
 ,@y INT
 )
AS
BEGIN
 DECLARE @z INT

 SET @z = 0
 SET @z = @x / @y

 PRINT ' The Output is:' + Cast(@z AS VARCHAR)
END

OutPut:
               EXEC div 100 ,20
         EXEC div 100,0

To resolve it:

               CREATE PROCEDURE DIV (
 @X INT
 ,@Y INT
 )
AS
BEGIN
 BEGIN TRY
  DECLARE @Z INT

  SET @Z = 0
  SET @Z = @X / @Y

  PRINT 'TEH OUTPUT IS:' + CAST(@Z AS VARCHAR)
 END TRY

 BEGIN CATCH
  PRINT ERROR_MESSAGE()
 END CATCH
END

Note:

We can write our own user defined error messages

CREATE PROCEDURE DIV (
 @X INT
 ,@Y INT
 )
AS
BEGIN
 BEGIN TRY
  DECLARE @Z INT

  SET @Z = 0
  SET @Z = @X / @Y

  PRINT 'TEH OUTPUT IS:' + CAST(@Z AS VARCHAR)
 END TRY

 BEGIN CATCH
  PRINT ERROR_MESSAGE()
 END CATCH
END

OutPut:
                EXEC DIVIX 100 ,1

Note:
                Raiserror statement raises the error but still net statement gets executed. Now if you want to stop the execution on the same line the code has to be enclosed within try catch blocks

CREATE PROCEDURE DIVIX (
 @X INT
 ,@Y INT
 )
AS
BEGIN
 BEGIN TRY
  DECLARE @Z INT

  SET @Z = 0

  IF @Y = 1
   RAISERROR (
     'CANNOT DIVIDE BY 1'
     ,15
     ,1
     )

  SET @Z = @X / @Y

  PRINT 'THE O/P IS:' + CAST(@Z AS VARCHAR)
 END TRY

 BEGIN CATCH
  PRINT ERROR_MESAGE()
 END CATCH
END

OutPut:

EXEC DIVIX 1001 ,1
               
Restrictions:

                Only member of sysadmin,db_owner or db_ddladmin can create & execute SP