如果行有关系,如何插入BIT值

时间:2012-09-19 10:27:29

标签: sql tsql insert sql-server-2008-r2

我有3个表BusStop,BusRoute和Stop_Route(用于M-2-M关系)。有些停靠点没有关系(路由),我需要更新BusStop表中Bit值为1或0的每条记录,具体取决于它是否有关系。我有一个查询来选择所有没有关系的站点:

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列类型的Bit我需要插入该值。

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:0)

您可以执行类似

的操作
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)