如何使用VBA和&amp ;;插入2个表ProductOrder和ProductOrderLine Excel中的外键

时间:2012-05-28 11:36:51

标签: sql sql-server excel vba foreign-keys

我是一个使用VBA / FK / SQL服务器的newbiew。我在excel中创建简单的采购订单工作簿用户界面。

我创建了两个表:

CREATE TABLE [dbo].[PurchaseOrder](
[PKPurchaseOrderID] [bigint] IDENTITY(1,1) NOT NULL,
[PurchaseOrderNumber] [bigint] NULL,
[PurchaseOrderDate] [date] NULL,
[PurchaseOrderTime] [int] NULL,
[PurchaseOrderSupplierID] [nvarchar](50) NULL,
[ShipToA1] [nvarchar](50) NULL,
[ShipToA2] [nvarchar](50) NULL,
[ShipToA3] [nvarchar](50) NULL,
[ShipToA4] [nvarchar](50) NULL,
 CONSTRAINT [PK_PurchaseOrder] PRIMARY KEY CLUSTERED 
(
    [PKPurchaseOrderID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF,     
ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

CREATE TABLE [dbo].[PurchaseOrderLines](
[PKPurchaseOrderLineID] [bigint] IDENTITY(1,1) NOT NULL,
[FKPurchaseOrderID] [bigint] NULL,
[Quantity] [smallint] NULL,
[Item] [nchar](25) NULL,
[Description] [nvarchar](50) NULL,
[siteID] [nchar](10) NULL,
[UnitPrice] [money] NULL,
[LineTotal] [money] NULL,

 CONSTRAINT [PK_PurchaseOrderLines] PRIMARY KEY CLUSTERED 

(

    [PKPurchaseOrderLineID] ASC

)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, 
ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]

) ON [PRIMARY]



ALTER TABLE [dbo].[PurchaseOrderLines]  WITH CHECK ADD  CONSTRAINT 
[FK_PurchaseOrderLines_PurchaseOrder] FOREIGN KEY([FKPurchaseOrderID])

REFERENCES [dbo].[PurchaseOrder] ([PKPurchaseOrderID])


ALTER TABLE [dbo].[PurchaseOrderLines] CHECK CONSTRAINT 
[FK_PurchaseOrderLines_PurchaseOrder]

GO

当用户点击按钮时,我希望在后台实现这一目标。

我不确定如何将PurchaseOrder表中创建的全新行与PurchaseorderLine表中的FK相关联。

我打算为单一用户界面做些什么:

  1. 插入新订单
  2. 使用Max(PKPurchaseOrderID)作为新订单行表的FK。
  3. 如果多个用户同时工作/提交订单,如何确定当前插入的订单ID(PKPurchaseOrderID)。如果我使用我的计划,恐怕可能会将订单行分配给不同的订单。例如

    请告知。

    我使用SQL Server 2008和Excel 2007/2010

    非常感谢

1 个答案:

答案 0 :(得分:1)

我会创建一个插入新行的存储过程,并返回带有SCOPE_IDENTITY()

的ID

这里有一篇关于不同"身份"的文章。 SQL Server中的方法。

http://blog.sqlauthority.com/2007/03/25/sql-server-identity-vs-scope_identity-vs-ident_current-retrieve-last-inserted-identity-of-record/