2012-08-10 50 views
0

我有一個必須插入到3個表中的表單。我創建了一個存儲過程(這是不正確的)。存儲過程使用ID插入到3個表

3表:
1. dbo.Client(客戶端ID,CLIENTNAME,AddressID
2. dbo.Contact(AddressID,Addressline1,ADD2,CityID)CityID來自DROPDOWNLIST。
3. dbo.PointOfCContact(POCID,名字......)

我的存儲過程..

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 [email protected]) 
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 [email protected]; 

IF NOT EXISTS(Select 1 FROM dbo.Client Where [email protected]) 
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 

得到一個錯誤:列名或提供值的數目不匹配表定義。

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

回答

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

+0

'INSERT INTO dbo.Contact(地址1,Adddres2,CityID) VALUES(@ Addressline1,@ Addressline2,@CityID); SET @AddressID = SCOPE_IDENTITY();插入到dbo.Client(ClientID,AddressID,CityID) VALUES(@ClientID,@AddressID,@CityID); ' 你的意思是這樣嗎? – Girish 2012-08-10 14:58:09

+0

@Girish是的。您應該將列名添加到所有INSERT語句。 – podiluska 2012-08-10 15:02:31

+0

謝謝,工作!希望我能投票給你.. – Girish 2012-08-10 15:15:06

0

您必須添加結構表;列添加到表

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