错误消息4145,级别15,状态1,非布尔类型的表达式

时间:2012-12-10 19:43:16

标签: sql sql-server syntax error-handling boolean

当我尝试执行此语句时,我收到以下错误消息:

  

Msg 4145,Level 15,State 1,Procedure tr_check_qty,Line 8
  在预期条件的上下文中指定的非布尔类型的表达式,在'BEGIN'附近

之前我收到过此错误消息,但这次我无法弄清楚如何修复它。我甚至有一个人为了这个目的而活着看,当他筋疲力尽,忙碌时,他找不到我的语法问题。救命啊!

CREATE TRIGGER tr_check_qty
ON order_details
FOR INSERT, UPDATE
AS
   IF (SELECT quantity_in_stock
       FROM products
       WHERE quantity_in_stock >= units_on_order)
   BEGIN
      PRINT 'Insert/Update Not Allowed: quantity_in_stock less than units_on_order.'
      ROLLBACK TRANSACTION
   END;
GO

好的,我现在可以执行此声明:

CREATE TRIGGER      tr_check_qty
ON                  order_details
FOR INSERT, UPDATE
AS
IF EXISTS           (   SELECT      COUNT(inserted.order_id)
                    FROM        inserted
                    INNER JOIN  products ON products.product_id=inserted.product_id
                    WHERE       inserted.quantity>products.quantity_in_stock)
BEGIN
PRINT 'Insert/Update Not Allowed: quantity_in_stock less than units_on_order.'
ROLLBACK TRANSACTION
END;
GO

但现在我收到了这个错误:

  

Msg 245,Level 16,State 1,Line 1   将varchar值'quantity'转换为数据类型int时,转换失败。

当我尝试在触发器之后执行此语句时:

UPDATE order_details
SET quantity=30
WHERE order_id=10044 AND product_id=7;
GO

2 个答案:

答案 0 :(得分:1)

您的if声明无法比较。也许你的意思是这样的:

IF   EXISTS (   SELECT      quantity_in_stock
                FROM        products
                WHERE       quantity_in_stock >= units_on_order )

查看是否返回任何行。

答案 1 :(得分:1)

我认为您也需要引用插入的行,例如here

CREATE TRIGGER tr_check_qty
3>    ON order_details
4>    FOR INSERT, UPDATE
5> AS
6>    IF EXISTS
7>       (
8>        SELECT 'True'
9>        FROM Inserted i
10>        JOIN products p
11>          ON i.ID = p.ID
          WHERE       quantity_in_stock >= units_on_order
12>       )
13>    BEGIN
14>        PRINT 'Insert/Update Not Allowed: quantity_in_stock less than units_on_order.'
15>        ROLLBACK TRAN
16> END