2

我正在尝试将数据插入到一个 SQL Server 存储过程中的多个表中。我还使用已插入数据的表中的身份,然后通过将这些身份写入另一个表来解决多对多关系。

从理论上讲,存储过程似乎存在逻辑,但在执行时只执行了第一个插入语句。请任何人都可以帮助解决这个问题。

存储过程如下:

Create Procedure [dbo].[InsertAllCustomerDetails]
(
    --@CustomerID Bigint output,
    @Firstname varchar(100),
    @LastName varchar(100),
    @Initials varchar(10),
    @Title varchar(20),
    @DateCreated datetime,
    @isDeleted Bit,
    --@ContactNumberID BIGINT Output,
    @ContactNumber Varchar(100),
    @ContactTypeID bigint,
    @Street Varchar(550),
    @AreaID BIGINT,
    @isPreferred Bit
    --@AddressID Bigint OutPut
)
AS

Insert Into Customer
(
    FisrtName,
    LastName,
    Initials,
    [Title],
    DateCreated,
    isDeleted
)
Values
(
    @Firstname,
    @LastName,
    @Initials,
    @Title,
    @DateCreated,
    @isDeleted
)
Declare @CustomerID BIGINT 
SELECT   @CustomerID = @@IDENTITY
       RETURN @CustomerID
--This will now insert the contact details for the customer
Insert Into ContactNumber
(
    ContactNumber,
    ContactTypeID
)
Values
(
    @ContactNumber,
    @ContactTypeID
)
Declare @ContactNumberID BIGINT 
SELECT   @ContactNumberID = @@IDENTITY
--This will insert into the CustomerContactNumber
Insert Into CustomerContactNumber
(
    ContactNumberID,
    CustomerID
)
Values
(
    @ContactNumberID,
    @CustomerID
)
--This will insert the address
Insert Into [Address]
(
    Street,
    AreaID,
    isPreferred
)
Values
(
    @Street,
    @AreaID,
    @isPreferred
)
Declare @AddressID BIGINT 
SELECT   @AddressID = @@IDENTITY
--This will insert the relationship for the customer Address table
Insert into CustomerAddress
(
    CustomerID,
    AddressID
)
Values
(
    @CustomerID,
    @AddressID
)
4

1 回答 1

2

我看到两件事:

  1. 您似乎在Customer插入中有错字:

    Insert Into Customer
    (
        FisrtName,   <-- should be FirstName?
        LastName,
    
  2. RETURNCustomer插入之后 - 这就是为什么只有第一个运行

    Declare @CustomerID BIGINT 
    SELECT   @CustomerID = @@IDENTITY
           RETURN @CustomerID     <----   This exits the sproc
    --This will now insert the contact details for the customer
    Insert Into ContactNumber
    

我猜这RETURN是为了调试而没有被删除,因为它被缩进遮住了。

于 2013-07-16T20:24:17.267 回答