子查询中的SQL更新

时间:2014-08-25 19:01:42

标签: sql-server join sql-update

我试图遍历表v中的所有行并将ExitPage设置为子查询的值,如下所示:

UPDATE JTrack_Visits v 
SET ExitPage = (SELECT TOP 1 page 
                FROM JTrack_VisitItems vi 
                WHERE vi.VisitId = v.visitid 
                ORDER BY vi.DatetimeLast DESC) 

这不会运行,任何人都可以帮助使用正确的语法吗?

2 个答案:

答案 0 :(得分:0)

尝试

UPDATE JTrack_Visits
   SET ExitPage = vi.page
FROM JTrack_Visits v
cross apply (
    SELECT TOP 1 page 
    FROM JTrack_VisitItems vi 
    WHERE vi.VisitId = v.visitid 
    ORDER BY vi.DatetimeLast DESC
 ) vi(page)

答案 1 :(得分:0)

你可以使用cte来构建你的结果集,然后像这样合并到目标表中:

use [chamomile]; 
go 
-- 
if object_id(N'tempdb..##jtrack_visits', N'U') is not null 
  drop table ##jtrack_visits; 
go 
create table ##jtrack_visits ( 
  [visit_id]    [int] 
  , [exit_page] [nvarchar](100) null 
  ); 
insert into ##jtrack_visits 
            ([visit_id] 
             , [exit_page]) 
values      (1 
             , null), 
            (5 
             , null), 
            (7 
             , null); 
go 
-- 
if object_id(N'tempdb..##jtrack_visititems', N'U') is not null 
  drop table ##jtrack_visititems; 
go 
create table ##jtrack_visititems ( 
  [visit_id]        [int] 
  , [page]          [sysname] 
  , [last_datetime] [datetime] 
  ); 
go 
-- 
insert into ##jtrack_visititems 
            ([visit_id] 
             , [page] 
             , [last_datetime]) 
values      (1 
             , N'page 1a' 
             , current_timestamp), 
            (1 
             , N'page 1b' 
             , datediff(day, -10, current_timestamp)), 
            (1 
             , N'page 1c' 
             , datediff(day, -1, current_timestamp)), 
            (7 
             , N'page 7a' 
             , datediff(day, -1, current_timestamp)); 
-- 
with [get_last_record] 
     as (select [jtrack_visititems].[visit_id] as [visit_id] 
                , [jtrack_visititems].[page]   as [page] 
                , [jtrack_visits].[exit_page]  as [exit_page] 
         from   (select [visit_id] 
                        , [page] 
                        , row_number() 
                            over ( 
                              partition by [visit_id] 
                              order by [last_datetime] desc) as [row_number] 
                 from   ##jtrack_visititems) as [jtrack_visititems] 
                join ##jtrack_visits as [jtrack_visits] 
                  on [jtrack_visits].[visit_id] = [jtrack_visititems].[visit_id] 
         where  [jtrack_visititems].[row_number] = 1) 
merge into ##jtrack_visits as target 
using [get_last_record] as source 
on target.[visit_id] = source.[visit_id] 
when matched then 
  update set target.[exit_page] = source.[page]; 
-- 
select * 
from   ##jtrack_visits;