我正在创建一个存储过程,在这里我要输入一个雇员和一个经理。如果经理不在employee表中,则需要添加他,然后可以添加employee。如果经理已经在表中,那么我只需将经理的EmployeeID
作为ManagerID
这是我的存储过程:
CREATE PROCEDURE dbo.CreateEmployee (
@DepartmentID INT,
@EmployeeFirstName NVARCHAR(25),
@EmployeeLastName NVARCHAR(25),
@Salary MONEY = 30000,
@ManagerFirstName NVARCHAR(25),
@ManagerLastName NVARCHAR(25)
)
AS
BEGIN;
SET NOCOUNT ON;
SET XACT_ABORT ON;
DECLARE @ManagerID INT;
SELECT @ManagerID = dbo.GetEmployeeID (@ManagerFirstName, @ManagerLastName);
IF (@ManagerID = NULL)
BEGIN;
INSERT INTO dbo.Employees (FirstName, LastName)
VALUES (@ManagerFirstName, @ManagerLastName)
SELECT @ManagerID = dbo.GetEmployeeID(@ManagerFirstName, @ManagerLastName)
INSERT INTO dbo.Employees (DepartmentID, FirstName, LastName, Salary, ManagerEmployeeID)
VALUES (@DepartmentID, @EmployeeFirstName, @EmployeeLastName, @Salary, @ManagerID)
END;
ELSE
BEGIN;
INSERT INTO dbo.Employees (DepartmentID, FirstName, LastName, Salary, ManagerEmployeeID)
VALUES (@DepartmentID, @EmployeeFirstName, @EmployeeLastName, @Salary, @ManagerID)
END;
END;
GO
当我测试我的程序时,它会罚款Employee,但不会增加我输入的经理。
这是我的测试方式:
EXECUTE dbo.CreateEmployee
@DepartmentID = 1,
@EmployeeFirstName = 'Brock',
@EmployeeLastName = 'Rigby',
@Salary = 120000,
@ManagerFirstName = 'Bob',
@ManagerLastName = 'Barker'
如果有人可以帮助我,那就太好了。如果您需要更多信息,请在下面评论。
答案 0 :(得分:1)
在SQL Server中,Brock要检查NULL,必须使用IS NULL
或IS NOT NULL
而不是@ManagerId = null(当您需要将值设置为NULL时,这是一种语法)。这可能是问题所在。
IF (@ManagerID IS NULL)-- this! you would never enter if block with @managerId = null
BEGIN;
INSERT INTO dbo.Employees (FirstName, LastName)
VALUES (@ManagerFirstName, @ManagerLastName)
SELECT @ManagerID = dbo.GetEmployeeID(@ManagerFirstName, @ManagerLastName)
INSERT INTO dbo.Employees (DepartmentID, FirstName, LastName, Salary, ManagerEmployeeID)
VALUES (@DepartmentID, @EmployeeFirstName, @EmployeeLastName, @Salary, @ManagerID)
END;
ELSE
BEGIN;
INSERT INTO dbo.Employees (DepartmentID, FirstName, LastName, Salary, ManagerEmployeeID)
VALUES (@DepartmentID, @EmployeeFirstName, @EmployeeLastName, @Salary, @ManagerID)
END;