从while循环(光标)中选择临时表

时间:2015-12-01 21:39:39

标签: sql-server tsql loops cursor

我试图基本上“联合”我的光标的结果集。由于我无法弄清楚如何“联合”它们,我想,嘿,为什么不将结果存储到临时表中,然后只从临时表中select *?问题是,当我运行此代码时,它表示我的临时表已经存在。我想当我做select into时,每次尝试创建一个新的临时表。如何在不使用select into的情况下插入临时表?

drop table #mikemarks
declare db_cursor CURSOR FOR SELECT jobid from cxxxxxxx.Campaign_Data_Extension_Names
declare @jobid int
open db_cursor
fetch next from db_cursor into @jobid while @@FETCH_STATUS = 0
begin
    select j.jobid as 'JobID', j.subscriberkey as 'EmailAddress', j.createddate as 'EventDate', jc.errorcode as 'ErrorCode', jc.Description as 'ErrorCodeDescription' into #mikemarks
    from jobsubscribererror j with (nolock)
    inner join jobsubscribererrorcode jc on j.errorcodeid = jc.errorcodeid
    where j.jobid = @jobid
    fetch next from db_cursor into @jobid
end
close db_cursor
deallocate db_cursor

1 个答案:

答案 0 :(得分:3)

如果在临时表中需要它,可以在单个语句中执行此操作,而不是循环。这样的事情。

select j.jobid as 'JobID'
    , j.subscriberkey as 'EmailAddress'
    , j.createddate as 'EventDate'
    , jc.errorcode as 'ErrorCode'
    , jc.Description as 'ErrorCodeDescription' 
into #mikemarks
from jobsubscribererror j
inner join jobsubscribererrorcode jc on j.errorcodeid = jc.errorcodeid
join cxxxxxxx.Campaign_Data_Extension_Names n on j.jobid = n.jobid