我正在探索在存储过程中使用表值参数在单次调用数据库时执行多次插入操作。如何在SQL Server 2008中设置插入期间创建int ID
表值参数包含的信息或多或少反映了我想要插入的表的定义。它只是缺少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
如何改变什么,我要插入如果我的参数中有多个数据集,则使用唯一标识符?
现在,如果我通过存储过程与表中没有以前的记录运行下面的语句
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
我怎样才能有效地做到这一点,而不使用的身份?
使用'IDENTITY'是最好的**唯一可靠的方法**来做到这一点。为什么你明确排除这种方法? – 2013-03-14 18:28:04
业务需求 – scottmgerstl 2013-03-14 18:32:51
业务*错误* – Kermit 2013-03-14 18:35:05