Sql Server TVP与Where / Case语句合并

时间:2015-06-11 14:19:38

标签: sql sql-server sql-server-2008 table-valued-parameters

我正在做的事情非常直接在几个帖子上挖掘,并且无法弄清楚如何正确地表达它

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

收到错误

  

消息10714,级别15,状态1,过程Update_SubdivisionNames,第17行   “WHEN MATCHED”类型的操作在MERGE语句的“UPDATE”子句中不能出现多次。

3 个答案:

答案 0 :(得分:2)

我大多在这里猜测,但似乎这些行的简单更新应该接近你想要做的事情。

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

答案 1 :(得分:2)

或者,如果你坚持crossOrigin: true陈述:

MERGE

答案 2 :(得分:1)

你不需要合并。您需要条件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