插入两个表同时插入新记录

时间:2014-09-17 13:24:35

标签: sql sql-server tsql stored-procedures

我有两个SQL Server表可以在我的数据库中使用。

这是我的表VMA_VehicleDetails_TB

CREATE TABLE [dbo].[VMA_VehicleDetails_TB] 
(
    [VehRegID]   INT            IDENTITY (1000, 2) NOT NULL,
    [TraPNumber] NVARCHAR (60)  NOT NULL,
    [VehOwner]   NVARCHAR (60)  NOT NULL,
    [RegExpDate] DATE           NOT NULL,
    [InsExpDate] DATE           NOT NULL,
    [VehModel]   NVARCHAR (120) NOT NULL,
    [VehOrigin]  NVARCHAR (120) NOT NULL,
    [VehType]    NVARCHAR (80)  NOT NULL,
    PRIMARY KEY CLUSTERED ([VehRegID] ASC)
);

这是我的表VMA_VehDrvAssigned_TB

CREATE TABLE [dbo].[VMA_VehDrvAssigned_TB] 
(
    [VehRegID]   INT DEFAULT ((0)) NOT NULL,
    [DrvRegID]   INT DEFAULT ((0)) NOT NULL,
    [IsAssigned] BIT DEFAULT ((0)) NOT NULL,
    CONSTRAINT [PK_VMA_VehDrvAssigned_TB] PRIMARY KEY CLUSTERED ([VehRegID] ASC)
);

我已使用此存储过程将新注册的车辆ID添加到VMA_VehDrvAssigned_TB表。它工作正常。

ALTER PROCEDURE [dbo].[addNewVehicleDetail_SP]
    @TraPNumber     NVARCHAR (60)
    ,@VehOwner      NVARCHAR (60)
    ,@RegExpDate    DATE
    ,@InsExpDate    DATE
    ,@VehModel      NVARCHAR (120)
    ,@VehOrigin     NVARCHAR (120)
    ,@VehType       NVARCHAR (80)
    ,@IsAssigned    BIT
    ,@DrvRegID      VARCHAR(60)
AS
BEGIN
    SET NOCOUNT ON;

    -- Insert statements for procedure here
    INSERT INTO [VMA_VehicleDetails_TB] (TraPNumber, VehOwner, RegExpDate, InsExpDate, VehModel, VehOrigin, VehType) 
    VALUES (@TraPNumber, @VehOwner, @RegExpDate, @InsExpDate, @VehModel, @VehOrigin, @VehType)

    INSERT INTO VMA_VehDrvAssigned_TB (VehRegID)
        SELECT 
            VehRegID = scope_identity();
END

现在,我想在插入新记录时将@IsAssigned@DrvRegID添加到同一个表中。但是,我只知道在表中添加单列。我错了吗?

1 个答案:

答案 0 :(得分:1)

只需修改上一个INSERT。

ALTER PROCEDURE [dbo].[addNewVehicleDetail_SP]
    -- Add the parameters for the stored procedure here
    @TraPNumber     NVARCHAR (60)
    ,@VehOwner      NVARCHAR (60)
    ,@RegExpDate    DATE
    ,@InsExpDate    DATE
    ,@VehModel      NVARCHAR (120)
    ,@VehOrigin     NVARCHAR (120)
    ,@VehType       NVARCHAR (80)
    ,@IsAssigned    BIT
    ,@DrvRegID      VARCHAR(60)
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
    -- Insert statements for procedure here
    INSERT INTO [VMA_VehicleDetails_TB] (TraPNumber,VehOwner,RegExpDate,InsExpDate,VehModel,VehOrigin,VehType) 
    VALUES (@TraPNumber,@VehOwner,@RegExpDate,@InsExpDate,@VehModel,@VehOrigin,@VehType)
    INSERT INTO VMA_VehDrvAssigned_TB (VehRegID, DrvRegID, IsAssigned )
    SELECT scope_identity(), @DrvRegID, @IsAssigned ;
END