MCDBA Brasil


  • Home
  • Sobre
  • Contato

Livros





Links Rápidos

SQL Server Builds (All Versions/Editions)


Download SQL Server 2017 (trial)


SQL Server 2017 Feature Pack


SQL Server 2016 Feature Pack


Cumulative Update SQL Server 2017 builds


Cumulative Update SQL Server 2016 builds


Cumulative Update SQL Server 2014 builds


Cumulative Update SQL Server 2012 builds


SQL Server 2005/2008 Samples Databases


Documentando o Servidor SQL Server


Analisando a Performance do Servidor-CheckList


Virtual PASS PT


Faça parte do maior virtual chapter do PASS com conteúdos técnicos em Português sobre SQL Server.

Todos os meses um evento Online para você! Acompanhe aqui os WebCasts já agendados

Sindicalize seu blog ou site ao VirtualPASSPT

SQL Server Blogs

SQL Server Query Processing Team


SQL Programmability & API Development Team


SQL Server Manageability Team


Latin America Support Team


Database + Disk + Performance


Microsoft SQL Server Support


SQL CLR Team


SQL Query Optimization Team


SQL 2005 Code Samples


SQL Server Express Team


SQL SMO Samples


SQL Storage Engine Team


SQL CAT Team


SQL Protocols Team


PSS SQL Server Engineers


Slava Oks on SQLOS


Ken Henderson’s blog


LUTI@Microsoft Blog


kimberly L. Trip’s blog


Fernando Garcia Blog

Dica da Semana

Substituindo Cursores no SQL Server 2000

por Nilton Pinheiro julho 25, 2004 Nenhum comentário

Exemplos:


Query utilizando cursor:


declare x cursor for select au_id, au_fname,au_lname from authors
declare @au_id varchar(20)
declare @au_fname varchar(50)
declare @au_lname varchar(50)
open x
Fetch next from x into @au_id,@au_fname,@au_lname
while @@fetch_Status=0
Begin
      select @au_id,@au_fname,@au_lname
      Fetch next from x into @au_id,@au_fname,@au_lname
end
close x
deallocate x


Esta mesma query pode ser reescrita utilizando-se tabelas temporárias ou funções MIN e MAX:


Tabela Temporária:


declare @au_id char( 11 )
set rowcount 0
select au_id,au_lname,au_fname into #mytemp from authors
set rowcount 1
select @au_id = au_id from #mytemp
while @@rowcount <> 0
begin
     set rowcount 0
     select au_id,au_lname,au_fname from #mytemp
     where au_id = @au_id 
     delete #mytemp where au_id = @au_id 
     set rowcount 1 
     select @au_id = au_id from #mytemp
end
set rowcount 0


Função MIN:


declare @au_id char( 11 )
select @au_id = min( au_id ) from authors
while @au_id is not null
begin
      select au_id,au_lname,au_fname from authors
      where au_id = @au_id
      select @au_id = min( au_id ) from authors
      where au_id > @au_id
end


Função MAX:


declare @au_id char( 11 )
select @au_id = max( au_id ) from authors
while @au_id is not null
begin
      select au_id,au_lname,au_fname from authors 
      where au_id = @au_id
      select @au_id = max( au_id ) from authors
      where au_id < @au_id
end


Os quatro algoritmos fazem o tratamento dos dados da tabela authors linha por linha. No entanto, os três últimos são bem mais rápidos do que o algorítimo que utiliza cursor.


Caso seja imprescindível a utilização de cursor, tente reduzir ao máximo o número de registros processados. Uma saída  para resolver este problema é primeiro mover os registros que você precisa para uma tabela temporária e então utilizar o cursor sobre estes e não na tabela original. Quanto menor o número de registros processados, mais rápido o cursor finalizará a execução.

Avaliação:
Compartilhe:
  • Anterior Tratando Erros em Procedures Aninhadas18 anos atrás
  • Próximo Utilizando Tabelas Temporárias no SQL Server 200018 anos atrás

Deixe uma resposta Cancelar resposta

O seu endereço de e-mail não será publicado. Campos obrigatórios são marcados com *

MVP Reconnect Award

Categorias

  • Artigos (359)
  • Dica da Semana (95)
  • Documentação (54)
  • Downloads (113)
  • MSDE 2000 (3)
  • Sem categoria (1)
  • Tutoriais (9)

Posts recentes

  • #FechouBrasil #PartiuPortugal
  • Brigando com o erro “The cached MSI file is missing”
  • MCDBABRASIL está de volta
  • Documentando o Servidor SQL Server
  • Brigando com os Erros 17182, 17826 e 17120

SQL Server AlwaysOn Video Series

Video1: Introdução ao SQLServer2012 AlwaysOn


Video2: Introdução ao SQLServer2012 AlwaysOn Availability Group


Video3: Introdução ao SQLServer2012 AlwaysOn AVG-Demo


Video4: Introdução ao SQLServer2012 AlwaysOn Listener


Video5: Introdução ao SQLServer2012 AlwaysOn Readable Secondaries


Video6: Introdução ao SQLServer2012 AlwaysOn Readable Secondaries-Demo


Video7: Introdução ao SQLServer2012 AlwaysOn Failover Clustering


Serie SQL Server Failover Clustering End-to-End

Parte 1: Configuração da Rede e Ambiente


Parte 2: Configurando o Windows 2008 R2 Domain Controler e DNS


Parte 3: Preparando os nós para o Failover Cluster


Parte 4: Configurando um Failover Cluster de 2 nós


Parte 5: Configurando as LUNs no iSCSI Software Target (Parte 1)


Parte 6: Configurando as LUNs no iSCSI Software Target (Parte 2)


Parte 7: Apresentando as LUNs para os nós do Failover Cluster


Parte 8: Configurando os discos no Failover Cluster


Parte 9: Instalando a primeira instância virtual do SQL Server 2008


Parte 10: Instalando a segunda instância virtual do SQL Server 2008


Parte 11: Instalando e Configurando o MSDTC no Failover Cluster


Parte 12: Configurando Mount Points no Cluster e SQL Server 2008


Vídeo Extra: Removendo uma Instância do SQL Server 2008 R2 em Cluster


Alta Disponibilidade no SQL Server 2008 R2: Failover Clustering Overview


Alta Disponibilidade no SQL Server 2008 R2: Failover Clustering na Prática

Menu

  • Home
  • Sobre
  • Contato

Mais

  • RSS Feeds
2022 MCDBA Brasil.