我正在尝试使用不同范围的数据运行查询,但是由于某种原因,当我运行它时,它会返回错误说明:
消息2714,级别16,状态6,第54
行在数据库中已经有一个名为“ ## contacts”的对象。
我将如何解决?是数据库中已创建的列还是我需要删除的列?
我正在使用的代码:
use KBData
go
declare
@startdate datetime='2010-01-01',
@enddate datetime = '2020-05-26';
/*from contacts*/
select
lower(c.contactid) as contactid ,
replace(replace(lower(c.emailaddress1),' ',''),',','') as emailaddress1,
replace(replace(lower(c.emailaddress2),' ',''),',','') as emailaddress2,
replace(replace(lower(c.emailaddress3),' ',''),',','') as emailaddress3
into ##contacts
from crm.Contact c
where (c.createdonutc >= @startdate and c.createdonutc < dateadd(dd,1,@enddate))
and (c.emailaddress1 is not null or c.emailaddress2 is not null or c.emailaddress3 is not null)
/*from buyers*/
select
lower(b.Email) as email
into #sales
from crm.SalesAgreement s
left join dbo.BuyerContracts bc
join dbo.buyers b
on b.ProspectNo = bc.ProspectNo
and b.Deleted is null
on s.kb_salesagreementnumber = bc.SalesAgreementNo
and bc.Deleted is null
where (s.kb_saledate >= @startdate and s.kb_saledate < dateadd(dd,1,@enddate))
and s.Deleted is null ;
select
distinct replace(replace(lower(b.email),' ',''),',','') as email
into #buyers
from #sales b
where b.Email is not null ;
您遇到的问题源于使用全局临时表(##tableName
)而非本地临时表(#tableName
)。两者的行为不同。
本地临时表是动态创建的,只能从创建它的会话中访问,并且在该会话关闭其连接时将被删除,或者除非在此之前被明确删除。它完全包含在该范围内。
全局临时表也在运行中创建,但是可以通过与服务器的任何连接访问。例如(我今天早些时候刚刚做过),您可以在一个SSMS窗口中创建一个全局临时表,然后在其他多个SSMS窗口中使用该表。或者您团队中的其他人也可以使用它。该表将一直存在,直到访问该表的最后一个会话断开连接为止,或者除非在此之前已将其明确删除,否则该表也将一直存在。
因此,如果您在运行此代码的情况下打开了两个会话,则##contacts
当第二个会话尝试创建它时,一个会话中的from会话将已经存在。在某些情况下,您需要全局临时表,并且需要在这些情况下进行存在性检查,但这种情况很少而且相去甚远。使用本地临时表通常更容易。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句