Sql 服务器 TVP 与 Where/Case 语句合并

Sql Server TVP Merge with Where/Case Statement

我做的事情很直接,在几个帖子里翻来覆去,想不出如何恰当地表达它

TVP 宣言

 CREATE TYPE [dbo].[CustomSeoDic] as table (
 [RecordID] [int] NULL,
 [Name] [nvarchar](125) NULL)
 GO

尝试 1

    BEGIN
        MERGE INTO Listings L
        USING @CustomSeo AS Tvp 
            ON Listings.ListingID = @CustomSeo.RecordID

        WHEN MATCHED AND L.OriginalSubdivisionName IS NULL THEN 
            UPDATE SET 
            L.OriginalSubdivisionName = L.SubdivisionName 
        WHEN MATCHED AND L.OriginalSubdivisionName IS NOT NULL THEN 
            UPDATE SET 
            L.SubdivisionName = Tvp.Name    
     END

尝试 2

   BEGIN
        MERGE INTO Listings L
        USING @CustomSeo AS Tvp 
            ON Listings.ListingID = @CustomSeo.RecordID

        WHEN MATCHED AND L.OriginalSubdivisionName IS NULL THEN 
            UPDATE SET 
            CASE L.OriginalSubdivisionName IS NULL THEN L.OriginalSubdivisionName = L.SubdivisionName 
            CASE L.OriginalSubdivisionName IS NOT NULL THEN L.SubdivisionName = Tvp.Name    
    END

收到错误

Msg 10714, Level 15, State 1, Procedure Update_SubdivisionNames, Line 17 An action of type 'WHEN MATCHED' cannot appear more than once in a 'UPDATE' clause of a MERGE statement.

我主要是在猜测这里,但似乎沿着这些方向进行的简单更新应该接近您尝试做的事情。

UPDATE l
SET OriginalSubdivisionName = CASE WHEN l.OriginalSubdivisionName IS NULL THEN L.SubdivisionNam ELSE Tvp.Name END
FROM Listing l
JOIN @CustomSeo Tvp ON Tvp.RecordID = l.ListingID

您不需要 MERGE。您需要条件 SET ColumnX = (this or that) 语句。

像这样。

Update Listings

Set L.OriginalSubdivisionName =
case when L.OriginalSubdivisionName IS NULL Then
L.SubdivisionName
else
L.OriginalSubdivisionName / * a little trick to keep it the same value */
end
,
L.SubdivisionName = 
case
    when L.OriginalSubdivisionName IS NOT NULL
        then Tvp.Name 
    else
    L.SubdivisionName / * a little trick to keep it the same value */
End

From
Listings L 
join
@CustomSeo AS Tvp 
            ON Listings.ListingID = @CustomSeo.RecordID

或者,如果您坚持 MERGE 声明:

BEGIN
    MERGE INTO Listings L
    USING @CustomSeo AS Tvp 
        ON Listings.ListingID = @CustomSeo.RecordID

    WHEN MATCHED 
        UPDATE SET 
        L.OriginalSubdivisionName = CASE WHEN L.OriginalSubdivisionName IS NULL 
                                         THEN L.SubdivisionName 
                                         ELSE Tvp.Name END
END