在插入/值/输出块中包含CASE

时间:2018-02-26 10:43:02

标签: sql sql-server tsql

我有以下T-SQL:

DECLARE @INSERTED_BOOKS table (
  BookId int,
  Image varbinary(max),
  Preview varbinary(max)
)

MERGE Books_Destination AS d
USING Books_Source AS s
ON 0 = 1
WHEN NOT MATCHED
THEN INSERT (Author, BookCategoryId, Title)
VALUES (s.Author, s.CategoryId, s.Title)
OUTPUT INSERTED.Id, s.Image, s.Preview
INTO @INSERTED_BOOKS;

我需要将s.CategoryId的转换集成到d.BookCategoryId:

case 
  when CategoryId = 1 then 2
  when CategoryId = 5 then 8
  when CategoryId = 14 then 6
  when CategoryId = 22 then 9

我的问题是如何将此CASE集成到我的插入代码中。

1 个答案:

答案 0 :(得分:2)

使用像ON 0=1这样的条件你强迫一个"总是INSERT"那么为什么不插入?

INSERT Books_Destination (Author, BookCategoryId, Title)
OUTPUT INSERTED.Id, INSERTED.Image, INSERTED.Preview INTO @INSERTED_BOOKS
SELECT Author, 
     case 
     when CategoryId = 1 then 2
     when CategoryId = 5 then 8
     when CategoryId = 14 then 6
     when CategoryId = 22 then 9
     END, Title
FROM Books_Source;

但是对于MERGE无论如何..把案例放到源定义中,这样你可以使用它,比如说,你想稍后更新并只有一个CASE

MERGE Books_Destination AS d
USING (
   SELECT Author, 
     case 
     when CategoryId = 1 then 2
     when CategoryId = 5 then 8
     when CategoryId = 14 then 6
     when CategoryId = 22 then 9
     END AS BookCategoryId, Title, Image, Preview
FROM Books_Source
) AS s ON 0 = 1
WHEN NOT MATCHED
THEN 
  INSERT (Author, BookCategoryId, Title)
  VALUES (s.Author, s.BookCategoryId, s.Title)
OUTPUT INSERTED.Id, s.Image, s.Preview INTO @INSERTED_BOOKS;