Skip to content
Advertisement

Trigger Not Running Check Whether it is correct or not? [closed]

This is my trigger and its running perfectly with the help of stackoverflow.com I edit my question because of blocking.

USE [Online Medical Store]
GO
/****** Object:  Trigger [dbo].[tr_issueBook]    Script Date: 4/7/2021 11:33:13 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER Trigger [dbo].[tr_issueBook] 
on [dbo].[IssueBooks] 
for insert  
AS 
Begin 
    Declare @IsbnNumber varchar 

    Select  @IsbnNumber = ISBN_Number from inserted
 
    update searchBooks set
        tbl_numberOfCopies =tbl_numberOfCopies - 1
    where tbl_IsbnBooks = @IsbnNumber
End

Advertisement

Answer

There are two issues with your trigger query

Issue 1. You didn’t declare the size for the variable

Declare @IsbnNumber varchar 

By not declaring the size, it is defaulted to 1. So any value assign to it will be truncated

Issue 2. You are assuming the inserted only contains 1 single row. Which infact might contain 0 to N depending on the insert statement

So your statement does not handle that

Select  @IsbnNumber = ISBN_Number from inserted

Your trigger should be just simply

update b 
set    tbl_numberOfCopies = tbl_numberOfCopies - 1
from   inserted i
       inner join searchBooks b on b.tbl_IsbnBooks = i.ISBN_Number 

You don’t need to declare a variable at all in your trigger query.


To answer your question on the varchar size, you should define it like

Declare @IsbnNumber varchar(10)

assuming that the size of the ISBNNumber is 10

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement