我需要同时执行更新/插入更改传入数据的结构。
考虑已定义一周中每一天的工作时间的商店。
希望这可以更好地解释我想要实现的目标:
worktimeOrigin表:
列:
- shop_id
- 天
- VAL
数据:
shop_id | day | val
------------------------------
123 | "monday" | "9:00 AM - 18:00"
123 | "tuesday" | "9:00 AM - 18:00"
123 | "wednesday" | "9:00 AM - 18:00"
购物台:
列:
- ID
- worktimeDestination.id
worktimeDestination表:
列:
- ID
- 星期一
- 星期二
- 星期三
我的目标:
我想将worktimeOrigin表中的数据插入到worktimeDestination中,并为shop指定适当的worktimeDestination。
商店表数据:
- 123
- 1(已更新)
worktimeDestination表数据:
id | monday | tuesday | wednesday
---------------------------------------------------------------------------
1 | "9:00 AM - 18:00" | "9:00 AM - 18:00" | "9:00 AM - 18:00" (inserted)
任何想法如何做到这一点?
答案 0 :(得分:2)
您可以使用PIVOT,例如
;WITH x AS
(
SELECT
ShopID,
[Monday] = [2],
[Tuesday] = [3],
[Wednesday] = [4]
FROM
(
SELECT
ShopID,
DW = CASE [Day]
WHEN 'Monday' THEN 2
WHEN 'Tuesday' THEN 3
WHEN 'Wednesday' THEN 4
END,
val
FROM
dbo.WorkTimeOrigin
-- WHERE ShopID = 123 or @param
) AS d
PIVOT
(
MAX(val)
FOR DW IN ([2],[3],[4])
) AS p
)
/*
INSERT dbo.WorkTimeDestination
(
id,
Monday,
Tuesday,
Wednesday
)
*/
SELECT
s.[WorkTimeDestination.ID],
[Monday],
[Tuesday],
[Wednesday]
FROM x
INNER JOIN dbo.Shop AS s
ON x.ShopID = s.id;
当您对结果感到满意时,取消注释INSERT部分。请注意,并非所有三行都必然存在,因此对于一个或多个值,最终可能会为NULL。