2015-11-29 80 views
-2

我試圖從不是服務器的員工創建阻止訂單。這是我的diagram該項目。我的代碼,我創建運行正常,但我還可以憑誰不是在「服務器」練習SQL CHECK CONSTRAINT with FUNCTION

CREATE FUNCTION dbo.chk_server_position(@employee_ID int) 
RETURNS varchar(50) 
AS 
BEGIN 
    DECLARE @position varchar(50); 
    DECLARE @employeeID int; 
    DECLARE @output varchar(50); 
    SELECT @position = employee.position, @employeeID = orderInfo.employee_ID 
    FROM employee, orderInfo 
    WHERE employee.employee_ID = orderInfo.employee_ID 
    IF (@position = 'server') 
     SET @output = 'true' 
    return @output; 
END; 
GO 

ALTER TABLE orderInfo 
ADD CONSTRAINT chk_position CHECK (dbo.chk_server_position(employee_ID) = 'true') 

顯然,我已經改變了代碼,這

CREATE FUNCTION dbo.chk_server_position(@employee_ID int) 
RETURNS varchar(50) 
AS 
BEGIN 
    DECLARE @position varchar(50); 
    DECLARE @employeeID int; 
    DECLARE @output varchar(50); 
    SET @employeeID = (SELECT employee_ID FROM orderInfo) 
    SET @position = (SELECT position FROM employee, orderInfo 
        WHERE employee.employee_ID = orderInfo.employee_ID AND employee.employee_ID = @employee_ID) 

    IF (@position = 'server') 
     SET @output = 'true' 
    return @output; 
END; 
GO 

員工插入和現在,我得到錯誤信息 子查詢返回多個值。當子查詢遵循=,!=,<,< =,>,> =或當子查詢用作表達式時,這是不允許的。 運行

ALTER TABLE orderInfo 
ADD CONSTRAINT chk_position CHECK (dbo.chk_server_position(employee_ID) = 'true') 

哪種方法更接近導致什麼時候?

回答

0

沒關係,我解決了這個問題TRIGGER

CREATE TRIGGER check_employee_position 
ON orderInfo 
INSTEAD OF INSERT 
AS 
BEGIN 
    DECLARE @position VARCHAR(50); 
    DECLARE @employeeID INT = (SELECT i.employee_ID FROM inserted i); 
    SET @position = (SELECT position FROM employee WHERE employee_ID = @employeeID) 
    IF (@position = 'server') 
     INSERT INTO orderInfo(employee_ID, tableNo) VALUES (@employeeID, (SELECT i.tableNo FROM inserted i)) 
END 
0

由於您的「上次選擇」員工不是服務器,您總是插入記錄,您錯過了給定員工的過濾。

您在USP的Where子句中沒有使用@employee_ID參數。 修改您的where子句,如: WHERE employee.employee_ID = orderInfo.employee_ID and employee.employee_ID = @employee_ID

更新: 爲什麼你需要選擇@EmployeeID在USP?你可以寫,就像下面:

CREATE FUNCTION dbo.chk_server_position(@employee_ID int) 
RETURNS varchar(50) 
AS 
BEGIN 
    DECLARE @position varchar(50); 
    DECLARE @output varchar(50) = 'false'; 

    SELECT @position = position FROM employee 
    inner join orderInfo ON employee.employee_ID = orderInfo.employee_ID 
    WHERE employee.employee_ID = @employee_ID) 

    IF (@position = 'server') 
     SET @output = 'true' 
    return @output; 

END; 
GO 
+0

試過了,仍然無法正常工作,我仍然可以插入EMPLOYEE_ID爲了誰不是「服務器「 –