2015-04-01 62 views
1

我有查詢這樣當子查詢如下>,> =,或當子查詢用作表達這是不允許的

CREATE TRIGGER check_shippeddate_tr 
    ON Orders 
    FOR UPDATE 
    AS 
    IF  ((SELECT ShippedDate FROM inserted) > (SELECT RequiredDate FROM Orders)) 
       BEGIN 
           PRINT 'Order must be shipped before required date' 
           ROLLBACK TRANSACTION 
       END 
       GO 

然而,當我嘗試更新表使用此代碼

UPDATE Orders 
    SET ShippedDate = '1994-04-03' 
    WHERE OrderID = 11051 
    AND  CustomerID = 'LAMAI' 
    AND  EmployeeID = 7 

它應該防止更新和打印郵件,因爲ShippedDate在RequiredDate之後。但是,我得到這個錯誤「子查詢返回的值超過1,當子查詢跟隨=,!=,<,< =,>,> =或當子查詢用作表達式時,這是不允許的。」How do我修復它?

+3

的錯誤信息很簡單:' SELECT foo FROM bar'返回結果的**表**而不是單個標量值。使用集合(例如'MAX'),添加一個'WHERE'條件來將其限制爲1個結果,或使用'SELECT TOP 1'。 – Dai 2015-04-01 22:31:26

+0

或者如果您打算對插入項目的ShippedDate> RequiredDate進行驗證,您可能希望'SELECT RequiredDate FROM inserted'。 – AaronLS 2015-04-01 22:51:26

+0

@戴我試過這樣((選擇TOP 1發貨日期\t從插入)>(選擇TOP 1 RequiredDate從訂單)),當我嘗試更新它。它始終激活觸發器並打印消息。我該怎麼做? – Lenic 2015-04-01 23:16:55

回答

1

試着這麼做.....

假設訂單ID是主鍵列

CREATE TRIGGER check_shippeddate_tr 
ON Orders 
FOR UPDATE 
AS 
BEGIN 
    SET NOCOUNT ON; 
IF EXISTS (SELECT 1 FROM inserted i 
      inner join Orders o ON i.OrderID = o.OrderID 
      WHERE i.ShippedDate > O.RequiredDate) 
     BEGIN 
         PRINT 'Order must be shipped before required date' 
         ROLLBACK TRANSACTION 
     END 

END 
+0

謝謝,這個工作。 – Lenic 2015-04-01 23:17:27

0

你的桌子上創建一個檢查約束

ALTER TABLE Orders 
ADD CHECK (ShippedDate < RequiredDate) 
相關問題