I need to create a new customer and Association (from the newly created customer to another customer) via a stored procedure.
My tables
CREATE TABLE Customers (
CustomerId int NOT NULL IDENTITY(1,1) PRIMARY KEY,
CustomerTypeId int NOT NULL,
FirstName varchar(20) NOT NULL,
LastName varchar(20) NOT NULL,
DateOfBirth date NOT NULL,
AddressLine1 varchar(60) NOT NULL,
City varchar(20) NOT NULL,
Country varchar(20) NOT NULL,
PhoneNumber int NOT NULL,
Email varchar(20) NOT NULL,
CONSTRAINT FK_CustomerTypeId FOREIGN KEY (CustomerTypeId) REFERENCES Reference (ReferenceId)
)
CREATE TABLE Association (
AssoId int NOT NULL IDENTITY(1,1) PRIMARY KEY,
AssoTypeId int NOT NULL,
Cust1Id int NOT NULL,
Cust2Id int NOT NULL,
CONSTRAINT FK_Customer1Id FOREIGN KEY (Cust1Id) REFERENCES Customers (CustomerId),
CONSTRAINT FK_Customer2Id FOREIGN KEY (Cust2Id) REFERENCES Customers (CustomerId),
CONSTRAINT BothClientsUnique UNIQUE (Cust1Id,
Cust2Id),
CONSTRAINT FK_AssoTypeId FOREIGN KEY (AssoTypeId) REFERENCES Reference (ReferenceId))
CREATE TABLE Reference (
ReferenceId int NOT NULL IDENTITY(1,1) PRIMARY KEY,
RefType varchar(20) NOT NULL,
RefDescription varchar(30),
Deleted bit NOT NULL default '0',
DeletedON date NULL)
I have attempted to created the stored procedure and got an error
Msg 121, Level 15, State 1, Procedure usp_NewCustNewAsso, Line 46
The select list for the INSERT statement contains more items than the insert list. The number of SELECT values must match the number of INSERT columns.
My Code
CREATE PROCEDURE dbo.usp_NewCustNewAsso@CustomerTypeId int,
@FirstName varchar(20),
@LastName varchar(20),
@DateOfBirth date,
@AddressLine1 varchar(60),
@City varchar(20),
@Country varchar(20),
@PhoneNumber int,
@Email varchar(20),
@AssoTypeId int,
@Cust1Id int,
@Cust2Id int
AS
Begin
Set Nocount On
DECLARE @CustomerId int
INSERT INTO [dbo].[Customers] ([CustomerTypeId], [FirstName], [LastName], [DateOfBirth], [AddressLine1], [City], [Country], [PhoneNumber], [Email])
SELECT @CustomerTypeId, @FirstName, @LastName, @DateOfBirth, @AddressLine1, @City, @Country, @PhoneNumber, @Email
SELECT
@CustomerId=@@IDENTITY
FROM[dbo].[Customers] C
LEFT outer JOIN
[dbo].[Association] A
onC.[CustomerId] = A.[Cust1Id]
INSERT INTO [dbo].[Association] ([AssoTypeId], [Cust2Id])
SELECT @AssoTypeId, @Cust1Id, @Cust2Id
End