将数据插入3个相关表中

时间:2010-11-02 02:02:49

标签: sql sql-server tsql

如何将数据插入3个相关表(SQL Server)

例如,我有表Customer< - Customer_Address - >地址 将数据插入Customer和Address后,如何将Customer和Address中的ID插入Customer_Address? (加入表)

谢谢!

6 个答案:

答案 0 :(得分:3)

使用SCOPE_IDENTITY,@@ IDENTITY可以从任何范围返回值:

DECLARE @CustomerId INT
DECLARE @AddressId INT

BEGIN TRANSACTION

  INSERT INTO CUSTOMER (blah, blah) values (blah, blah)
  SET @CustomerId = SCOPE_IDENTITY

  INSERT INTO ADDRESS (blah, blah) values (blah, blah)
  SET @AddressId = SCOPE_IDENTITY 

  INSERT INTO CUSTOMERADDRESS (CustomerId,AddressId) values (@CustomerId,@AddressId)

COMMIT TRANSACTION

答案 1 :(得分:1)

如果要插入多行,可以使用输出子句:

declare @insertedAddresses table (OriginalID int, AddressID int);
declare @insertedCustomers table (OriginalID int, CustomerID int);

insert into dbo.Addresses (AddressData)
output source.OriginalID, inserted.AddressID into @insertedAddresses
select AddressData from source;

insert into dbo.Customers (CustomerData)
output source.OriginalID, inserted.CustomerID into @insertedCustomers
select CustomerData from source;

insert into dbo.Customer_Address (AddressID, CustomerID)
select a.AddressID, c.CustomerID
from @insertedAddresses a inner join @insertedCustomers c on c.OriginalID=a.OriginalID;

答案 2 :(得分:0)

如果Customer和Address表中的ID是Identity列,则可以将新ID存储到变量中。

DECLARE @CustomerID int

SELECT @CustomerID = @@IDENTITY FROM TABLE CUSTOMER

类似的语法可用于Address表。然后在INSERT语句中,您可以执行此操作:

INSERT INTO Customer_Address (CustomerID, AddressID)
VALUES (@CustomerID, @AddressID)

答案 3 :(得分:0)

使用交易,并记住身份。在sql server中 -

declare @CustomerId int
declare @AddressId int

begin tran
    insert into Customer (blah, blah) values (blah, blah)
    set @CustomerId = @@IDENTITY    --assuming there are no triggers
    insert into [Address] (blah, blah) values (blah, blah)
    set @AddressId = @@IDENTITY     --once again, no triggers to mess up the @@IDENTITY
    insert into CustomerAddress(CustomerId,AddressId) values (@CustomerId,@AddressId)
commit

答案 4 :(得分:0)

这是一种方式。

Declare CustomerID int, AddressID int

insert into Customer (list, of, fields) values (list, of, values) select @CustomerID=scope_Identity() insert into Address (list, of, fields) values (list, of, values) select @AddressID =scope_Identity()

insert into Customer_Address (CustomerID, AddressID) values (@CustomerID, @AddressID)

答案 5 :(得分:0)

如果是应用程序,为什么不使用Linq,你可以在几分钟内以更加压缩的方式完成这样的事情,并且更加大胆地使用业务逻辑模型。

如果不是,我强烈建议使用事务和SCOPE_IDENTITY版本,因为如果您处于负载较重的系统中,则其他操作可以执行插入并更改标识值,因此您将以不一致的数据结束。