Sql server SQL Server 2008 R2:奇数游标行为
我必须从电子表格中快速地将一些数据加载到数据库中,并且需要使用光标。光标有一些奇怪的副作用,我不完全确定为什么会发生这种情况。如果有人能解释,我将不胜感激 当使用ORDERBY子句时,游标运行了324次(对于我的数据集来说是正确的次数)。没有orderby,光标只运行了81次。当测量Id在没有select语句的情况下发生更改时,几乎看起来select语句针对光标进行了重新计算 代码如下:Sql server SQL Server 2008 R2:奇数游标行为,sql-server,sql-server-2008,cursor,Sql Server,Sql Server 2008,Cursor,我必须从电子表格中快速地将一些数据加载到数据库中,并且需要使用光标。光标有一些奇怪的副作用,我不完全确定为什么会发生这种情况。如果有人能解释,我将不胜感激 当使用ORDERBY子句时,游标运行了324次(对于我的数据集来说是正确的次数)。没有orderby,光标只运行了81次。当测量Id在没有select语句的情况下发生更改时,几乎看起来select语句针对光标进行了重新计算 代码如下: declare t cursor for SELECT SurveyID, attributenam
declare t cursor for
SELECT SurveyID, attributename, attributevalue FROM tempCAVImport cav
left outer join activitylog al on al.entityid = cav.surveyid and al.systemactivitytypeid = 19
where al.activitylogid is null
order by cav.surveyid --this was not in the statement originally
open t
fetch next from t
into @surveyId, @name, @value
declare @count int = 0
while @@Fetch_Status = 0
Begin
delete from @additionalInfo
insert into @additionalInfo (AttributeName, AttributeValue, EntityId)
select 'ClientAttributeName', @name, @surveyId
insert into @additionalInfo (AttributeName, AttributeValue, EntityId)
select 'ClientAttributeValue', @value, @surveyId
EXEC [InsertActivityLogEntry] null, 'Assigned Extended Attribute', 'Survey', @surveyId, null, @additionalInfo
set @count = @count + 1
print(@count)
fetch next from t
into @surveyId, @name, @value
End
close t
deallocate t
一些数据:
SurveyID AttributeName AttributeValue
11545575 Contacted Since Delivery NO
11545575 Finance Used xxx
11545575 Recommend Dealer NEUTRAL
11545575 Recommend xxx NEUTRAL
11545575 Recommend Finance NEUTRAL
11545575 Unresolved Problems NO
11626821 Contacted Since Delivery YES
11626821 Finance Used xxx
11626821 Recommend Dealer PROMOTER
11626821 Recommend xxx PROMOTER
11626821 Recommend Finance NEUTRAL
您的光标正在从循环光标的代码插入的表中进行选择-假定[InsertActivityGentry]插入光标所连接的表activitylog 这肯定会给你带来麻烦,除非你以某种方式控制秩序
也许这就是order by帮助您解决问题的原因:)这里还有一件事——现在我有点猜测,当您在游标上有order by时,游标必须由查询执行器100%预取——但是当您有物理顺序时,它可以以更慢的方式获取,但是插入的影响更大。只是另一个角度。是的-动态和静态游标。没有索引支持的order by将在工作表中预先评估静态order by。伙计们,谢谢。做了一些进一步的挖掘,发现有很多选项可以选择如何定义游标获取数据的方式(静态与动态等)。我在猜测您的specifyanorderby子句是否会更改游标使用的默认抓取选项的类型,这与Martin所说的差不多……更改正在循环的数据集可能是个坏主意。你需要确保你知道你在做什么(循环结构是缓存的,或者顺序是这样的,这样你就不会改变剩下来遍历的数据集)。我通常不喜欢使用游标,但这是我很快拼凑起来完成一个小的一次性任务的东西。