0

我正在探索在存储过程中使用表值参数在对数据库的一次调用中进行多次插入。

表值参数包含的信息或多或少反映了我要插入的表的定义。它只缺少 ID 列。

如果我有下表定义:

Create Table Product
(
     ProductID int,
     ProductName varchar(100),
     ProductDesc varchar(4000),
     ProductCost int
)

类型定义:

Create Type ProductTable as Table
(
    ProductName varchar(100),
    ProductDesc varchar(4000),
    ProductCost int
)

和存储过程定义:

Create Procedure usp_Product_Insert
    @Products ProductTable READONLY
AS
    INSERT Product
    (
        ProductID,
        ProductName,
        ProductDesc,
        ProductCost
    )
    SELECT
        (Select ISNULL(Max(ProductID),0) + 1 From Product),
        P.ProductName,
        P.ProductDesc,
        P.ProductCost
    FROM
        @Products P

如果我的参数中有多个数据集,如何更改必须插入唯一 ID 的内容?

现在,如果我运行以下语句

Truncate Table Product
Declare @Products ProductTable
Insert @Products Values ('Playstation', 'Game Console', 300)
exec usp_Product_InsertUpdate_WithOutput @Products

通过表中没有以前记录的存储过程,我得到

ProductID   ProductName ProductDesc ProductCost
1           Playstation     Game Console    300

但如果我运行不止一张唱片

Truncate Table Product
Declare @Products ProductTable
Insert @Products Values
('Playstation', 'Game Console', 300),
('Xbox', 'Game Console', 200),
('Wii', 'Game Console', 150)
exec usp_Product_InsertUpdate_WithOutput @Products

我明白了

ProductID   ProductDesc     ProductDesc ProductCost
1           Playstation     Game Console    300
1           Xbox            Game Console    200
1           Wii             Game Console    150

我想看到的是

ProductID   ProductDesc     ProductDesc ProductCost
1           Playstation     Game Console    300
2           Xbox            Game Console    200
3           Wii             Game Console    150

在不使用身份的情况下如何有效地完成此任务?

4

2 回答 2

4

你不能。甚至不应该尝试。

业务定义业务键。

开发人员定义代理键

你想要的是一个代理键,所以使用一个IDENTITY列。

如果您的企业定义了代理键,那么您的职责是教他们不应该这样做。

于 2013-03-14T18:50:49.573 回答
0

经过进一步搜索,我发现了hiss056提供的这种方法

存储过程将被重写如下:

Create Procedure usp_Product_Insert
    @Products ProductTable READONLY
AS
    INSERT Product
    (
        ProductID,
        ProductName,
        ProductDesc,
        ProductCost
    )
    SELECT
        (ROW_NUMBER( ) OVER ( ORDER BY ProductID ASC )) + (Select ISNULL(Max(ProductID),0) From Product),
        P.ProductName,
        P.ProductDesc,
        P.ProductCost
    FROM
        @Products P
于 2013-03-14T18:34:28.977 回答