两个选择和两个插入一个SQL Server存储过程

时间:2011-03-24 13:04:00

标签: sql sql-server stored-procedures

我有一个程序,我将在下面写。现在我想添加两个选择。

首先,SELECT ID FROM Category Where CategoryName = ''将其保存在变量@CategoryID中。

第二个选择语句:SELECT ID FROM Type WHERE TypeName = ''并将其保存在@TypeID

现在我想添加第二个插页:

INSERT INTO Inventory(ProductID, InputQuantity, Margin, InputDateTime, ExpDate) 
VALUES(@ProductID, @Quantity,@Margin, @InputDateTime, @ExpDate) 
where ProductID = Scope_Identity()

谢谢:)

这是我的程序:

USE [AcidDB]
GO
/****** Object:  StoredProcedure [dbo].[InsertProducts]    Script Date: 03/24/2011 15:29:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROC [dbo].[InsertProducts]

@CategoryID int,
@TypeID int,
@BarCode NvarChar(MAX),
@ArtNumber NvarChar(MAX),
@ProductName NvarChar(MAX),
@Price Decimal(18, 2),
@SelfPrice Decimal(18, 2),
@PriceWithOutAWD Decimal(18, 2),
@UnitsInStock int,
@Comment NvarChar(MAX)

AS 

INSERT INTO Products(CategoryID, TypeID, BarCode, ArtNumber, ProductName, Price, SelfPrice, PriceWithOutAWD, UnitsInStock, Comment) 
VALUES(@CategoryID, @TypeID, @BarCode, @ArtNumber, @ProductName, @Price, @SelfPrice, @PriceWithOutAWD, @UnitsInStock, @Comment) 

Exec InsertProducts '','','','','','','','','',''
Select SCOPE_IDENTITY()

3 个答案:

答案 0 :(得分:3)

你不能在插页上有位置:

INSERT INTO Inventory(ProductID, InputQuantity, Margin, InputDateTime, ExpDate) 
VALUES(@ProductID, @Quantity,@Margin, @InputDateTime, @ExpDate) 
where ProductID = Scope_Identity()

将数据插入Product表后,将新的ProductId放入变量:

@ProductId = Scope_Identity()

然后,在插入中使用此变量:

INSERT INTO Inventory(ProductID, InputQuantity, Margin, InputDateTime, ExpDate) 
VALUES(@ProductID, @Quantity,@Margin, @InputDateTime, @ExpDate) 

答案 1 :(得分:1)

假设您的修改过程将传递categoryname和typename,那么我认为以下是您想要的。无需从Category和Type表中单独选择 - 只需将其作为第一个插入查询的一部分。

ALTER PROC [dbo].[InsertProducts]

@CategoryName nvarchar(max),
@TypeName nvarchar(max),
@BarCode NvarChar(MAX),
@ArtNumber NvarChar(MAX),
@ProductName NvarChar(MAX),
@Price Decimal(18, 2),
@SelfPrice Decimal(18, 2),
@PriceWithOutAWD Decimal(18, 2),
@UnitsInStock int,
@Comment NvarChar(MAX),
@Quantity int,
@Margin decimal(14,2),
@InputDateTime datetime,
@ExpDate datetime
AS 
declare @ProductID int

INSERT INTO Products(CategoryID, TypeID, BarCode, ArtNumber, ProductName, Price, SelfPrice, PriceWithOutAWD, UnitsInStock, Comment) 
select c.CategoryID, t.TypeID, @BarCode, @ArtNumber, @ProductName, @Price, @SelfPrice, @PriceWithOutAWD, @UnitsInStock, @Comment
from Category c cross join Type t
where c.CategoryName = @CategoryName and
t.TypeName = @TypeName

set @ProductID = SCOPE_IDENTITY()

INSERT INTO Inventory(ProductID, InputQuantity, Margin, InputDateTime, ExpDate) 
VALUES(@ProductID, @Quantity,@Margin, @InputDateTime, @ExpDate)

顺便说一下 - 你真的希望有人把罗密欧与朱丽叶的整个剧本作为产品名称吗? nvarchar(max)有它的位置,但它不应该盲目地用来避免考虑你的数据库中你想要允许的内容。

答案 2 :(得分:0)

@Damien_The_Unbeliever有正确的想法,但我建议您使用try catch块和事务。当您有多个需要作为一个组一起工作的事务时,它们应该包含在一个显式事务中,如果失败则回滚。否则您将遇到数据完整性问题。您不希望这会进入产品,然后在库存中失败。有关如何执行此操作,请参阅联机丛书。

相关问题