Arquivo
Novo artigo no Simple-Talk
New article at Simple-Talk, thriller than ever to talk about Spool Operator and Halloween Problem, here is an little preview…
To show the functionality of the Eager Spool we’ll go back in time a bit, to the time when I was just a project being planned, but some other geeks working intensively with databases.
It was Halloween; the cold winter’s night was black as pitch, (I really don’t know if was winter, but I thought it would sound more thrilling) and the wind howled in the trees. It was 1976 and the children was demanding “tricks or treat” in the houses. The full moon shone and illuminated the whole city when suddenly, some clouds crossed the moon making the night even more dark and gloomy. It was possible to smell and taste the tension in the air like a stretched rubber band so close to burst. People walking in the street felt that someone was observing them, and when they looked closely in their back, they see two red eyes waiting and looking out for a prey unprotected.
Was that their imagination? Or just the wrong night to work with databases?
See the Full Article here, http://www.simple-talk.com/content/article.aspx?article=1034
CASE + CTEs
Aaa que beleza, Sexta-feira… o dia começa melhor… todo mundo feliz… porque será?
Mas vamos lá… aproveitando o embalo que no último post falei sobre o CASE, vou dar outra dica.
Por ex:
CREATE FUNCTION dbo.fn_Situacao(ID Integer)
RETURNS TABLE
AS
RETURN (SELECT Col1,
Col2
CASE dbo.fn_SuperUltraFunctionRetornaTudo(@ID) WHEN ‘S’ THEN 1 ELSE –1 END as Status1,
CASE dbo.fn_SuperUltraFunctionRetornaTudo(@ID) WHEN ‘N’ THEN 0 ELSE –1 END as Status2
FROM Tab1
WHERE ID = @ID)
Repare que a function fn_SuperUltraFunctionRetornaTudo esta sendo utilizada duas vezes para o mesmo ID, ou seja tem um certo desperdício ai concorda? Se eu conseguir fazer com que a chamada desta function seja única, vou ganhar tempo… para isso podemos fazer o seguinte:
CREATE FUNCTION dbo.fn_Situacao(ID Integer)
RETURNS TABLE
AS
RETURN (WITH Temp_CTE (Situacao)
AS
(
SELECT dbo.fn_SuperUltraFunctionRetornaTudo(@ID)
)
SELECT Col1,
Col2
CASE Temp_CTE.Situacao WHEN ‘S’ THEN 1 ELSE –1 END as Status1,
CASE Temp_CTE.Situacao WHEN ‘N’ THEN 0 ELSE –1 END as Status2
FROM Tab1
CROSS JOIN Temp_CTE
WHERE ID = @ID)
Feito, usando a CTE eu tiro a duplicidade. Isso pode salvar seu dia…
Case + SubQueries
Galera, estes dias o MVP Adam Haines postou uma caso bem interessante que precisamos tomar cuidado.
SubQueries + CASE,
Veja um exemplo:
SELECT CASE (SELECT Col1 FROM Test)
WHEN 30 THEN ‘Pequeno’
WHEN 60 THEN ‘Médio’
ELSE ‘Grande’
END, *
FROM Test
Veja o plano de execução:
Ou seja, o SQL vai ler a tabela Test para cada opção no CASE, portanto cuidado. Uma alternativa para escrever esta consulta seria o seguinte:
SELECT (SELECT CASE Col1
WHEN 30 THEN ‘Pequeno’
WHEN 60 THEN ‘Médio’
ELSE ‘Grande’
END
FROM Test), *
FROM Test
Veja o plano de execução:
Captou a mensagem?
Abraços
Série Mentes Brilhantes – Parte 12
O que fazer quando você quer dar um ar mais profissional para seus Inserts?
Use um cursor para inserir os dados linha a linha
DECLARE tmp_Cursor CURSORSTATICREAD_ONLYLOCAL
FORSELECT Col1,
Col2,
Col3,
Col4,
Col5,
Col6,
Col7,
Col8
FROM dbo.fn_RetornaDados(@Col9,
@Col10,
@Col11,
@Col12)
OPEN tmp_Cursor;
FETCHNEXTFROM tmp_Cursor
INTO @Col1,
@Col2,
@Col3,
@Col4,
@Col5,
@Col6,
@Col7,
@Col8;
WHILE@@FETCH_STATUS= 0
BEGIN
INSERTINTO Tabela(Col1,
Col2,
Col3,
Col4,
Col5,
Col6,
Col7,
Col8)
VALUES (@Col1,
@Col2,
@Col3,
@Col4,
@Col5,
@Col6,
@Col7,
@Col8)
FETCHNEXTFROM tmp_Cursor
INTO @Col1,
@Col2,
@Col3,
@Col4,
@Col5,
@Col6,
@Col7,
@Col8;
END
CLOSE tmp_Cursor;
DEALLOCATE tmp_Cursor;
Kalen Delaney VS o mundo não técnico
Série Mentes Brilhantes – Parte 11
O que fazer quando você gosta muito de fazer selects?
Faça um select para ler cada coluna, desta forma você consegue deixar o código mais completo.
SELECT @ID_E = ID_E
FROM Tab1
INNER JOIN Tab2
ON Tab1.ID_Grupo = Tab2.ID_Grupo
WHERE Tab2.ID_Ass = 1;
SELECT @DT = DT,
@HR = HR,
@MN = MN,
@ID_G = ID
FROM Tab2
WHERE ID_Ass = 1;
SELECT @ID_A = ID_A
FROM Tab1
WHERE ID_G = 1;
What 5 things should SQL Server get rid of? Me too, why not?
O Paul Randal começou uma discussão bem interessante sobre 5 coisas que ele gostaria de remover do SQL Server.
Depois disso vários começaram a dar suas opiniões, no fim do post tem alguns links…
Desconsiderando alguns itens já mencionados pelo Paul e companhia, segue a minha lista de 5 coisas que deveriam morrer no SQL Server.
1. Permitir criar índices duplicados. SQL Server 2008 permite que você crie 999 índices exatamente iguais. Isso é ridículo.
Msg 1910, Level 16, State 1, Line 1
Could not create nonclustered index ‘ix_test1000’ because it exceeds the maximum of 999 allowed per table or view.
2. Botão play de Debug, cansei de contar quantas vezes já cliquei ou já reclamaram pra mim que clicaram no botão errado.
3. Arredondamento “automático” de campos Float no SSMS. Isso definitivamente causa confusões enormes. Várias vezes já me perguntaram… “ma que merda que tá acontecendo aqui?”
Query Analyzer
SQL Server Managment Studio
4. Essa é recente e já vai pra minha lista. Desculpe a palavra mas… Porra, acabou de lançar o R2 e já não posso restaurar um Backup feito no R2 no 2008 SP1. Que saco!
5. Por fim mas não menos importante, acho que deveriam remover o recurso de Paralelismo. Haha, Laerte e Fernando Garcia muita calma nessa hora, é brincadeira… 🙂
Por fim de verdade, SQL Server em Português ninguém merece. Definitivamente isso deve morrer. Ou no mínimo se é pra fazer faz direito.
E você o que acha? Qual é a sua lista?
Paul Randal – What 5 things should SQL Server get rid of?
Michelle Ufford – DELETE 5_Useless_Things FROM [SQL Server]
Lee Everest – Five things SQL Server should ban forever
Buck Woody – What 5 things should SQL Server get rid of?
Jonathan Kehayias – 5 Things SQL Server should get rid of
Lee Everest – Five things SQL Server should add
Mike Walsh – 5 Things SQL Server Should DROP
Aaron Bertrand – Tagged: 5 things SQL Server should drop
Thomas LaRock – What 5 things Should SQL Server Get Rid Of?
Brent Ozar – 5 Things SQL Server Should Truncate
Fabiano VS Reporting Services 2005
Por estes dias um de nossos clientes abriu um chamado dizendo que estava com um problema no Wizard do Reporting Services.
Ao tentar utilizar uma proc que usa uma tabela temporária, o Wizard retornava uma mensagem de erro dizendo que a tabela não existia, segue o print abaixo.
Quando fui analizar utilizei o SQL Server 2008 R2 que é a versão que esta instalada na minha máquina. Conclusão, não deu erro, veja abaixo:
Conclusão corrigiram a “cagada” no SQL 2008 R2, para resolver o problema, tive que incluir um no SET FMTONLY OFF; no início da procedure.
Por padrão o Reporting Services habilita o FMTONLY para que seja retornada somente o metada do código, porém neste caso da erro por causa da tabela temporária. Incluindo o OFF no início da proc resolvemos o problema.
Série Mentes Brilhantes – Parte 10
O que fazer quando você deseja apagar registro somente se ele existir na tabela?
Verifique se ele existe antes de apagar
IFEXISTS(SELECT 1 FROM Clientes WHERE ID_Cliente = @ID)
BEGIN
DELETEFROM Clientes WHERE ID_Cliente = @ID
END














