如果表达式比较不起作用

时间:2016-08-13 00:47:06

标签: sql sql-server

我想执行比较,如果@ accid2不等于@accid然后回滚动作,否则执行插入。

我的触发器的结果是,即使它不匹配,但它仍会插入到我的表中。

这是我的代码:

ALTER TRIGGER [dbo].[TG_checkacctypehtl]
ON [dbo].[Accommodation_Hotel] INSTEAD OF INSERT 
AS 
DECLARE @accid NVARCHAR(50), @accid2 NVARCHAR(50),@hid NVARCHAR(50),@fsp NVARCHAR(50), @fc NVARCHAR(50), @sr NVARCHAR(50);
SELECT  @hid = i.hotel_id FROM INSERTED i;  
SELECT @fsp = i.facillities_swimming_pool FROM INSERTED i;
SELECT @fc = i.facillities_catering FROM INSERTED i;
SELECT @sr =  i.star_rating FROM INSERTED i;
SELECT  @accid2 = i.accommodation_id FROM INSERTED i; 
SELECT  @accid = accommodation_id FROM [dbo].[Accommodation] WHERE    accommodation_type= 'hotel' AND accommodation_id=@accid2; 
BEGIN 
BEGIN TRAN
SET NOCOUNT ON
PRINT @accid2
PRINT @accid
IF(@accid2 != @accid)
BEGIN
RAISERROR('Record Not Inserted, Accommodation ID is not a Hotel Id',16,1);   ROLLBACK; END 
ElSE BEGIN
INSERT INTO [dbo].[accommodation_hotel] (hotel_id,facillities_swimming_pool,facillities_catering,star_rating,accommodation_id) 
        VALUES (@hid,@fsp,@fc,@sr,@accid2);COMMIT;

END
END

* print用于检查我得到的值。

是我的逻辑错误还是我的语法错误?

2 个答案:

答案 0 :(得分:1)

我会重写像这样的整个触发器......

ALTER TRIGGER [dbo].[TG_checkacctypehtl]
ON [dbo].[Accommodation_Hotel] 
INSTEAD OF INSERT 
AS 
BEGIN
  SET NOCOUNT ON;
INSERT INTO [dbo].[accommodation_hotel] (hotel_id,facillities_swimming_pool,facillities_catering,star_rating,accommodation_id) 
SELECT i.hotel_id 
      ,i.facillities_swimming_pool
      ,i.facillities_catering
      ,i.star_rating
      ,i.accommodation_id
FROM inserted i 
WHERE EXISTS ( SELECT 1 
               FROM [dbo].[Accommodation] a
               WHERE a.accommodation_type= 'hotel' 
               AND a.accommodation_id = i.accommodation_id)

IF EXISTS (SELECT 1 FROM inserted i 
            WHERE NOT EXISTS ( SELECT 1 
                               FROM [dbo].[Accommodation] a
                               WHERE a.accommodation_type= 'hotel' 
                               AND a.accommodation_id = i.accommodation_id)
            )
  BEGIN
    RAISERROR('Records with invalid Accommodation ID is not a Hotel Id not inserted',16,1);
  END
END

插入包含有效住宿ID的行,如果有任何行包含无效的酒店ID,则会引发错误,也不需要所有这些变量。

还会为每个事务触发触发器,而不是针对每一行触发触发器。您的代码假设一次只能在表中插入一行。

答案 1 :(得分:-1)

应为IF(@ accid2<> @accid)