存储过程使用ID插入3个表

时间:2012-08-10 14:47:56

标签: sql sql-server

我有一个必须插入3个表的表单。我创建了一个存储过程(这是不正确的)。

3表:
1. dbo.Client(ClientID,ClientName, AddressID
2. dbo.Contact(AddressID,Addressline1,Add2, CityID )CityID来自Dropdownlist。
3. dbo.PointOfCContact(POCCI,FirstName,...)

我的存储过程..

Create PROCEDURE sp_Clientdetails(
    @ClientName varchar(50),

    @Addressline1   varchar(50),
    @Addressline2   varchar(50),
    @CityID INT,

    @Firstname  varchar(50),
    @LastName   varchar(50),
    @Middlename  varchar(50),
    @Mob1 numeric(10,0),
    @Mob2 numeric(10,0),
    @Email1 varchar(50),
    @Email2 varchar(50),
    @phone varchar(50),
    @Extention INT  
    )
AS
DECLARE @AddressID int, @ClientID int, @POCID int;

Set NOCOUNT OFF

BEGIN TRANSACTION

IF NOT EXISTS(Select 1 FROM dbo.Contact Where AddressID=@AddressID)
BEGIN
    INSERT INTO dbo.Contact VALUES (@Addressline1, @Addressline2, @CityID);
    SET @AddressID = SCOPE_IDENTITY();
    SET @CityID = SCOPE_IDENTITY();
END
ELSE
    Select AddressID = @AddressID From dbo.Contact Where AddressID=@AddressID;

IF NOT EXISTS(Select 1 FROM dbo.Client Where ClientID=@ClientID)
BEGIN
    INSERT INTO dbo.Client VALUES (@ClientID, @AddressID, @CityID);
    SET @ClientID= SCOPE_IDENTITY();
END
ELSE
    Select ClientID = @ClientID From dbo.Client Where ClientID = @ClientID;

Insert into dbo.PointOfCContact VALUES (@Firstname, @LastName, @Middlename, @Mob1, @Mob2,
 @Email1, @Email2, @phone, @Extention);
SET @POCID= SCOPE_IDENTITY();

COMMIT

获取错误:列名或提供的值数与表定义不匹配。

on INSERT INTO dbo.Contact VALUES (@Addressline1, @Addressline2, @CityID);

2 个答案:

答案 0 :(得分:1)

您应指定列名

INSERT INTO dbo.Contact (Address1, Adddres2, CityID) 
VALUES (@Addressline1, @Addressline2, @CityID);

....

INSERT INTO dbo.Client (ClientID, AddressID, CityID)
VALUES (@ClientID, @AddressID, @CityID);  

更好的是,您可以使用MERGE语法 http://technet.microsoft.com/en-us/library/bb510625.aspx

答案 1 :(得分:0)

您必须添加结构表;将列添加到表

INSERT INTO dbo.Contact (Address1, Adddres2, CityID) VALUES (@Addressline1, @Addressline2, @CityID);