从TVP插入数据到表不起作用?

时间:2013-12-30 06:53:35

标签: sql sql-server sql-server-2012

我有下表,

CREATE TABLE [dbo].[ProductInventory](
    [ProductID] [int] NOT NULL,
    [SourceID] [int] NOT NULL,
    [Stock] [int] NULL,
)

CREATE TABLE [dbo].[Products](
    [ID] [int] NOT NULL,
    [ImpID] [int] NOT NULL,
   ...........................
)

CREATE TABLE [dbo].[Sources](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [Name] [nvarchar](225) NOT NULL,
    [Code] [varchar](225) NOT NULL
)

这是我简单的TPV,

CREATE TYPE DictionaryType AS TABLE
(
    [ID] INT
    ,[Key] NVARCHAR(MAX)
    ,[Value] NVARCHAR(MAX)
)

现在我要更新ProductInventory,

我需要的是使用DictionaryType TVP更新ProductInventory。这里@Inventory是DictionaryType TVP,

UPDATE  ProductInventory
    SET [Stock] = InvType.[Value]
FROM    @Inventory InvType
        INNER JOIN Products P ON (P.ImpID = InvType.ID)
        INNER JOIN [Sources] S ON (S.Code = InvType.[Key])
        INNER JOIN ProductInventory PIn ON (PIn.ProductID = P.ID AND PIn.SourceID = S.ID)
WHERE   PIn.ProductID IS NULL;

每件事都很好,但ProductInventory也可以包含SourceID = -1表示any-source。现在我的TVP可以包含Key(SourceID)= -1。如何更新上面的SQL以支持此功能?

1 个答案:

答案 0 :(得分:0)

请尝试:

UPDATE  ProductInventory
    SET [Stock] = InvType.[Value]
FROM    @Inventory InvType
        INNER JOIN Products P ON (P.ImpID = InvType.ID)
        INNER JOIN [Sources] S ON (S.Code = InvType.[Key])
        INNER JOIN ProductInventory PIn 
           ON (PIn.ProductID = P.ID AND PIn.SourceID = S.ID) 
                OR PIn.SourceID=-1  --<<<<CHANGE
WHERE   PIn.ProductID IS NULL;