2012-12-09 143 views
0

我想創建一個存儲過程以將數據插入到SQL Server中的2個表中。加入選擇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 

我曾嘗試加入在年底和我都找過了插入連接開始,不知道是否我只是得到它都是錯誤的。

我有一個部門表和人員表,我想我將能夠通過FK DepartmentID,我有Person表中訪問部門表,因爲在Department表

回答

1

我覺得PK像這樣的東西

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 
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 [email protected]_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 [email protected]_Department 
END