2012-12-10 26 views
0

當我嘗試和執行該語句我收到此錯誤信息:錯誤消息4145,15級,狀態1,非布爾類型的表達式

Msg 4145, Level 15, State 1, Procedure tr_check_qty, Line 8
An expression of non-boolean type specified in a context where a condition is expected, near '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 Conversion failed when converting the varchar value 'quantity' to data type int.

當我嘗試excecute觸發以下這種說法:

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

回答

1

您的if聲明沒有比較。也許你的意思是這樣的:

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

查看是否有任何行返回。

+0

你在這個觸發器沒有所謂的「量」的變化。目前還不清楚它指的是什麼。 quantity_in_stock和unis_on_order的數據類型是什麼? –

+0

他們都是int。激發此陳述的原始問題是:在order_details表上創建一個名爲tr_check_qty的INSERT和UPDATE觸發器,以僅允許庫存數量大於或等於訂單單位的產品訂單。運行以下查詢以驗證您的觸發器。 UPDATE order_details SET quantity = 30 WHERE order_id = 10044 AND product_id = 7; GO – isolatedhowl

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 
相關問題