0

我正在尝试创建一个存储过程来将数据插入到 SQL Server 中的 2 个表中。

我尝试将连接放在代码的所有不同位置,但仍然出现错误。

 CREATE PROCEDURE sp_Insert_Person
 @s_FirstName nvarchar(50),
 @s_Surname nvarchar(50),
 @s_AddressLine1 nvarchar(50),
 @s_AddressLine2 nvarchar(50),
 @s_Postcode nvarchar(10),
 @s_Phone nvarchar(50),
 @s_Department nvarchar(50)
 AS
BEGIN
INSERT INTO 
        tbl_person(FirstName, Surname, AddressLine1, AddressLine2, 
                   Postcode, Phone, tbl_Department.Department)
INNER JOIN tbl_person
ON  tbl_person.DepartmentID = tbl_Department.DepartmentID

VALUES (@s_FirstName,
        @s_Surname,
        @s_AddressLine1,
        @s_AddressLine2,
        @s_Postcode,
        @s_Phone,
        @s_Department)

END

我已经尝试了最后的连接,一开始我到处寻找插入连接,想知道我是不是弄错了。

我有一个部门表和一个人员表,并认为我可以通过DepartmentID我在人员表中的 FK 访问部门表,部门表中的 PK 也是如此

4

2 回答 2

1

我想这样的事情

INSERT INTO tbl_person
                     (FirstName,
                     Surname, 
                     AddressLine1, 
                     AddressLine2, 
                     Postcode, 
                     Phone, 
                     DepartmentID)
Select @s_FirstName,
        @s_Surname,
        @s_AddressLine1,
        @s_AddressLine2,
        @s_Postcode,
        @s_Phone, 
        tbl_Department.DepartmentID 
from  tbl_person 
join DepartmentID
ON  tbl_person.DepartmentID = tbl_Department.DepartmentID 
where tbl_Department.Department = @s_Department
于 2012-12-09T19:08:11.547 回答
0
 CREATE PROCEDURE sp_Insert_Person
 @s_FirstName nvarchar(50),
 @s_Surname nvarchar(50),
 @s_AddressLine1 nvarchar(50),
 @s_AddressLine2 nvarchar(50),
 @s_Postcode nvarchar(10),
 @s_Phone nvarchar(50),
 @s_Department nvarchar(50)
 AS
BEGIN
if not Exists(select * from tbl_Department where Department=@s_Department)
   insert into tbl_Department (Department) Values (@s_Department)

INSERT INTO tbl_person
                     (FirstName,
                     Surname, 
                     AddressLine1, 
                     AddressLine2, 
                     Postcode, 
                     Phone, 
                     DepartmentID)

select @s_FirstName,
        @s_Surname,
        @s_AddressLine1,
        @s_AddressLine2,
        @s_Postcode,
        @s_Phone,
        @s_Department,
        DepartmentID 
        from tbl_Department 
        where Department=@s_Department
END
于 2012-12-09T19:10:45.097 回答