Sql 如果行有关系,如何插入位值
我有3个表BusStop、BusRoute和Stop_Route(用于M-2-M关系)。有些站点没有关系(路由),我需要使用位值1或0更新BusStop表中的每个记录,这取决于它是否有关系。我有一个查询来选择所有没有关系的站点:Sql 如果行有关系,如何插入位值,sql,tsql,insert,sql-server-2008-r2,Sql,Tsql,Insert,Sql Server 2008 R2,我有3个表BusStop、BusRoute和Stop_Route(用于M-2-M关系)。有些站点没有关系(路由),我需要使用位值1或0更新BusStop表中的每个记录,这取决于它是否有关系。我有一个查询来选择所有没有关系的站点: SELECT BusStop.StopId FROM BusStop LEFT OUTER JOIN BusStop_BusRoute ON BusStop.StopId = BusStop_BusRoute.StopId WHERE
SELECT
BusStop.StopId
FROM
BusStop
LEFT OUTER JOIN BusStop_BusRoute
ON BusStop.StopId = BusStop_BusRoute.StopId
WHERE
BusStop_BusRoute.StopId IS NULL
但我不清楚如何根据这个结果增加价值。我已经读过CURSOR和CASE-WHEN语句,但我仍然不知道如何在我的案例中应用它们。有一个StopStatus列类型的位,我需要在其中插入该值 你可以做如下事情
UPDATE BusStop
SET StopStatus =
CASE
WHEN BusStop_BusRoute.StopID IS NULL THEN 0
ELSE 1
END
FROM
BusStop
LEFT JOIN BusStop_BusRoute
ON BusStop.StopId = BusStop_BusRoute.StopId
UPDATE BusStop SET BitValue = 0 WHERE StopID in
(
--your query
SELECT
BusStop.StopId
FROM
BusStop
LEFT OUTER JOIN BusStop_BusRoute
ON BusStop.StopId = BusStop_BusRoute.StopId
WHERE
BusStop_BusRoute.StopId IS NULL
)
下面是(我认为)与您类似的完整代码。
一张桌子。当i为1时,最后一个查询将位设置为1
create table aaa(id int identity, i int, j int, b bit)
insert into aaa values(1, 0, 0), (0, 0, 0), (0, 1, 0), (0, 0, 0)
select * from aaa
update aaa set b = 1 where id in (
select id from aaa where i = 1)