【问题标题】:How to insert BIT value if row has relation如果行有关系,如何插入 BIT 值
【发布时间】:2012-09-19 10:27:29
【问题描述】:

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

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 语句,但我仍然不知道如何在我的案例中应用它们。有一个 Bit 的 StopStatus 列类型,我需要在其中插入该值。

【问题讨论】:

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


    【解决方案1】:
    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
    

    【讨论】:

      【解决方案2】:

      你可以这样做

      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 时,最后一个查询将 bit 设置为 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)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-29
        • 1970-01-01
        • 2023-03-30
        • 2019-02-10
        相关资源
        最近更新 更多