加入选择SQL Server存储过程

时间:2012-12-09 19:03:21

标签: sql sql-server stored-procedures

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

我已经尝试将联接放在代码的所有不同位置,但仍然会出错。

 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

我已经尝试了最后的连接,并且在开始时我已经查看了所有插入连接,想知道我是否只是把它弄错了。

我有一个department表和一个person表,并且认为我可以通过Person表中的FK DepartmentID访问department表,就像Department表中的PK一样

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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