我在如何使用存储过程向一个客户添加多个位置时遇到问题。下面是我的表格,我使用索引来帮助我向一个客户添加多个位置,但我应该
SELECT @intLocationIndex = MAX(intLocationIndex) +1
太?
CREATE TABLE TCustomer
(
intCustomerID INTEGER NOT NULL,
strCustomerName VARCHAR(50) NOT NULL,
strAddress VARCHAR(50) NOT NULL,
CONSTRAINT TCustomer_PK PRIMARY KEY (intCustomerID)
)
CREATE TABLE TCustomerLocation
(
intLocationID INTEGER NOT NULL,
intLocationIndex INTEGER NOT NULL,
intCustomerID INTEGER NOT NULL,
CONSTRAINT TCustomerLocation_PK
PRIMARY KEY(intLocationID, intLocationIndex)
)
CREATE TABLE TLocation
(
intLocationID INTEGER NOT NULL,
strLocationName VARCHAR(50) NOT NULL,
strLocationAddress VARCHAR(50) NOT NULL,
strLocationCity VARCHAR(50) NOT NULL,
CONSTRAINT TLocation_PK PRIMARY KEY(intLocationID)
)
CREATE PROCEDURE uspAddCustomerLocation
@strCustomerName VARCHAR(50),
@strAddress VARCHAR(50),
@strLocationName VARCHAR(50),
@strLocationAddress VARCHAR(50),
@strLocationCity VARCHAR(50)
AS
BEGIN TRANSACTION
SET XACT_ABORT ON
DECLARE @intCustomerID INTEGER
SELECT @intCustomerID = MAX(intCustomerID) + 1
FROM TCustomer (TABLOCKX) -- LOCK TABLE UNTIL THE END OF TRANSACTION
SELECT @intCustomerID = COALESCE( @intCustomerID , 1)
INSERT INTO TCustomer (intCustomerID, strCustomerName , strAddress)
VALUES(@intCustomerID ,@strCustomerName ,@strAddress)
DECLARE @intLocationID INTEGER
DECLARE @intLocationIndex INTEGER
SELECT @intLocationID = MAX(intLocationID) + 1
FROM TLocation (TABLOCKX) -- LOCK TABLE UNTIL THEEND OF TRANSACTION
COMMIT TRANSACTION
GO
答案 0 :(得分:0)
我不是DBA,但我希望这些ID字段是IDENTITY字段。无论如何,我认为有问题的选择将是SELECT @intLocationIndex = MAX(intLocationIndex) +1 Where intCustomerID = @intCustomerID