Saturday 8 July 2017

Moving Average Ssas


A maioria das pessoas está familiarizada com a frase, isso vai matar dois pássaros com uma pedra. Se você não estiver, a fase se refere a uma abordagem que aborda dois objetivos em uma ação. (Infelizmente, a expressão em si é bastante desagradável, como a maioria de nós não deseja lançar pedras em animais inocentes). Hoje, I39m vai abranger alguns conceitos básicos em dois grandes recursos no SQL Server: o índice Columnstore (disponível apenas no SQL Server Enterprise) e O SQL Query Store. A Microsoft realmente implementou o índice Columnstore no SQL 2012 Enterprise, embora eles o aprimorem nos últimos dois lançamentos do SQL Server. A Microsoft apresentou o Query Store no SQL Server 2016. Então, quais são esses recursos e por que eles são importantes? Bem, eu tenho um demo que irá apresentar os dois recursos e mostrar como eles podem nos ajudar. Antes de ir mais longe, também cubro esse (e outros recursos do SQL 2016) no meu artigo da revista CODE sobre os novos recursos SQL 2016. Como uma introdução básica, o índice Columnstore pode ajudar a acelerar as consultas que exploram as quantidades de grandes quantidades de dados e A Query Store rastreia as execuções de consultas, os planos de execução e as estatísticas de tempo de execução que você normalmente precisa colecionar manualmente. Confie em mim quando eu digo, são excelentes recursos. Para esta demo, eu estarei usando o banco de dados de demonstração do Microsoft Contoso Retail Data Warehouse. Falando vagamente, o Contoso DW é como uma quota muito grande AdventureWorksquot, com tabelas contendo milhões de linhas. (A maior tabela AdventureWorks contém aproximadamente 100.000 linhas no máximo). Você pode baixar o banco de dados do Contoso DW aqui: microsoften-usdownloaddetails. aspxid18279. O Contoso DW funciona muito bem quando você deseja testar desempenho em consultas contra tabelas maiores. O Contoso DW contém uma tabela de fatos de data warehouse padrão chamada FactOnLineSales, com 12,6 milhões de linhas. Certamente, essa não é a maior mesa de armazenamento de dados do mundo, mas também não é uma criança. Suponha que eu quero resumir o valor das vendas do produto para 2009 e classificar os produtos. Eu posso consultar a tabela de fatos e juntar-se à tabela Dimensão do produto e usar uma função RANK, assim: Aqui, um conjunto de resultados parcial das 10 melhores linhas, por Total Sales. No meu laptop (i7, 16 GB de RAM), a consulta leva entre 3-4 segundos para ser executada. Isso pode não parecer o fim do mundo, mas alguns usuários podem esperar resultados quase instantâneos (da maneira que você pode ver resultados quase instantâneos ao usar o Excel contra um cubo OLAP). O único índice que eu atualmente tenho nesta tabela é um índice agrupado em uma chave de vendas. Se eu olhar para o plano de execução, o SQL Server faz uma sugestão para adicionar um índice de cobertura para a tabela: agora, só porque o SQL Server sugere um índice, não significa que você deve criar índices cegamente em todas as mensagens de indexação quotmissing. No entanto, nessa instância, o SQL Server detecta que estamos filtrando com base no ano e usando a chave de produto e a quantidade de vendas. Assim, o SQL Server sugere um índice de cobertura, com o DateKey como o campo da chave de índice. A razão pela qual chamamos isso de quotcoveringquot index é porque o SQL Server irá recorrer ao longo dos campos não-chave que usamos na consulta, quanto ao ridequot. Dessa forma, o SQL Server não precisa usar a tabela ou o índice em cluster em todo o mecanismo do banco de dados pode simplesmente usar o índice de cobertura para a consulta. Os índices de cobertura são populares em determinados cenários de banco de dados de dados e relatórios, embora eles tenham um custo do mecanismo de banco de dados, mantendo-os. Nota: Os índices de cobertura foram durante muito tempo, então eu ainda não abordava o índice Columnstore e a Query Store. Então, vou adicionar o índice de cobertura: se eu re-executar a mesma consulta que corri um momento (o que agregou o valor das vendas para cada produto), a consulta às vezes parece executar cerca de um segundo mais rápido e recebo uma Plano de execução diferente, que usa uma pesquisa de índice em vez de uma verificação de índice (usando a chave de data no índice de cobertura para recuperar vendas para 2009). Portanto, antes do Índice Columnstore, isso poderia ser uma maneira de otimizar essa consulta em versões muito antigas do SQL Server. Ele é executado um pouco mais rápido do que o primeiro, e eu recebo um plano de execução com um Index Seek em vez de um Index Scan. No entanto, existem alguns problemas: os dois operadores de execução, quotIndex Seekquot e quotHash Match (Aggregate), ambos operam essencialmente quotrow by rowquot. Imagine isso em uma mesa com centenas de milhões de linhas. Relacionado, pense no conteúdo de uma tabela de fatos: neste caso, um valor de chave de data único e um valor de chave de produto único podem ser repetidos em centenas de milhares de linhas (lembre-se, a tabela de fato também possui chaves para geografia, promoção, vendedor , Etc.) Então, quando o quotIndex Seekquot e quotHash Matchquot funcionam por linha, eles estão fazendo isso sobre valores que podem ser repetidos em muitas outras linhas. Normalmente, esse é o caso do I39d segue para o índice SQL Server Columnstore, que oferece um cenário para melhorar o desempenho desta consulta de maneiras surpreendentes. Mas antes que eu faça isso, let39s voltem no tempo. Let39s voltam para o ano de 2010, quando a Microsoft apresentou um suplemento para o Excel conhecido como PowerPivot. Muitas pessoas provavelmente se lembravam de mostrar demonstrações do PowerPivot para Excel, onde um usuário poderia ler milhões de linhas de uma fonte de dados externa para o Excel. O PowerPivot comprimiria os dados e forneceria um mecanismo para criar tabelas dinâmicas e gráficos dinâmicos que funcionavam a velocidades surpreendentes contra os dados compactados. O PowerPivot usou uma tecnologia em memória que a Microsoft denominou quotVertiPaqquot. Esta tecnologia em memória no PowerPivot basicamente levaria valores de chave de chave de negócios duplicados e comprimi-los para um único vetor. A tecnologia em memória também digitalizaria esses valores em paralelo, em blocos de várias centenas por vez. A linha inferior é que a Microsoft assustou uma grande quantidade de aprimoramentos de desempenho no recurso VertiPaq em memória para uso, à direita da caixa proverbial. Por que estou tirando esse pequeno passeio pela linha de memória Porque, no SQL Server 2012, a Microsoft implementou uma das características mais importantes no histórico de seu mecanismo de banco de dados: o índice Columnstore. O índice é apenas um índice apenas em nome: é uma maneira de tomar uma tabela do SQL Server e criar uma barra de colunas comprimida na memória que comprime os valores das chaves estrangeiras duplicadas para valores vetoriais únicos. A Microsoft também criou um novo conjunto de buffer para ler esses valores de vetores compactados em paralelo, criando o potencial de ganhos de desempenho enormes. Então, eu vou criar um índice de armazenamento de colunas na tabela, e eu verá o quanto melhor (e mais eficientemente) a consulta é executada, em relação à consulta que é executada contra o índice de cobertura. Então, eu criei uma cópia duplicada do FactOnlineSales (I39ll chamá-lo de FactOnlineSalesDetailNCCS), e I39ll crie um índice de armazenamento de colunas na tabela duplicada dessa maneira eu não interfiro com a tabela original e o índice de cobertura de qualquer maneira. Em seguida, eu crie um índice de armazenamento de colunas na nova tabela: Observe várias coisas: I39ve especificou várias colunas de chave estrangeiras, bem como a quantidade de vendas. Lembre-se de que um índice de armazenamento de colunas não é como um índice de linha-loja tradicional. Não há quotkeyquot. Estamos simplesmente indicando quais colunas o SQL Server deve comprimir e colocar em uma pasta de colunas na memória. Para usar a analogia do PowerPivot para o Excel quando criamos um índice de armazenamento de colunas, nós pedimos ao SQL Server que faça essencialmente o mesmo que o PowerPivot fez quando importámos 20 milhões de linhas para o Excel usando o PowerPivot Então, I39ll re-execute a consulta, desta vez usando A tabela duvidosa FactOnlineSalesDetailNCCS que contém o índice columnstore. Essa consulta é executada instantaneamente em menos de um segundo. E eu também posso dizer que, mesmo que a mesa tivesse centenas de milhões de linhas, ainda funcionaria no quotbat proverbial de um eyelashquot. Podemos olhar para o plano de execução (e em alguns momentos, vamos), mas agora é o momento de cobrir o recurso da Loja de consultas. Imagine por um momento, que executamos ambas as consultas durante a noite: a consulta que usou a tabela regular FactOnlineSales (com o índice de cobertura) e a consulta que usou a tabela duplicada com o índice Columnstore. Quando nos efetuamos o login na manhã seguinte, gostaríamos de ver o plano de execução para ambas as consultas, assim como as estatísticas de execução. Em outras palavras, gostaríamos de ver as mesmas estatísticas que poderíamos ver se executássemos ambas as consultas de forma interativa no SQL Management Studio, ativadas em TIME e IO Statistics, e visualizamos o plano de execução logo após a execução da consulta. Bem, isso é o que a Query Store nos permite fazer, podemos ativar (habilitar) o Query Store para um banco de dados, que irá acionar o SQL Server para armazenar a execução da consulta e planejar as estatísticas para que possamos visualizá-las mais tarde. Então, eu vou habilitar a Query Store no banco de dados Contoso com o seguinte comando (e I39ll também limpar qualquer cache): Então I39ll executar as duas consultas (e quotpretendquot que eu as executei há horas atrás): Agora vamos fingir que eles funcionaram horas atrás. De acordo com o que eu disse, a Query Store irá capturar as estatísticas de execução. Então, como eu os vejo Felizmente, isso é bastante fácil. Se eu expandir o banco de dados Contoso DW, I39ll verá uma pasta Query Store. A Query Store tem uma tremenda funcionalidade e tentei cobrir uma grande parte disso em postagens de blog subseqüentes. Mas por agora, eu quero ver estatísticas de execução nas duas consultas e examinar especificamente os operadores de execução para o índice de armazenamento de colunas. Então, eu vou clicar com o botão direito no Top Resource Consuming Queries e executar essa opção. Isso me dá um gráfico como o abaixo, onde posso ver o tempo de duração da execução (em milissegundos) para todas as consultas que foram executadas. Nessa instância, a Query 1 foi a consulta contra a tabela original com o índice de cobrança e o Query 2 foi contra a tabela com o índice de armazenamento de colunas. Os números que não são o índice de armazenamento de colunas superaram o índice de cobertura de tabela original por um fator de quase 7 a 1. Eu posso mudar a métrica para ver o consumo de memória. Nesse caso, observe que a consulta 2 (a consulta do índice de armazenamento de colunas) usou muito mais memória. Isso demonstra claramente por que o índice columnstore representa a tecnologia quotin-memoryquot. O SQL Server carrega todo o índice de armazenamento de colunas na memória e usa um pool de buffer completamente diferente com operadores de execução aprimorados para processar o índice. OK, então temos alguns gráficos para ver as estatísticas de execução, podemos ver o plano de execução (e os operadores de execução) associados a cada execução Sim, podemos se você clicar na barra vertical para a consulta que usou o índice columnstore, você verá a execução Plano abaixo. A primeira coisa que vemos é que o SQL Server realizou uma verificação de índice de armazenamento de colunas, e isso representou quase 100 do custo da consulta. Você pode estar dizendo, por um minuto, a primeira consulta usou um índice de cobertura e realizou um índice de busca, então, como uma verificação do índice de armazenamento de colunas pode ser mais rápida. Essa é uma questão legítima e, felizmente, isso é uma resposta. Mesmo quando a primeira consulta realizou um índice de busca, ele ainda executou quotrow by rowquot. Se eu colocar o mouse sobre o operador de varredura do índice de lojas de colunas, vejo uma dica de ferramenta (como a abaixo), com uma configuração importante: o Modo de Execução é BATCH (em oposição a ROW.) O que nós tivemos com a primeira consulta usando o Índice de cobertura). Esse modo BATCH nos diz que o SQL Server está processando os vetores compactados (para quaisquer valores de chave estrangeiros duplicados, como a chave do produto e a chave da data) em lotes de quase 1.000, em paralelo. Portanto, o SQL Server ainda é capaz de processar o índice columnstore muito mais eficientemente. Além disso, se eu colocar o mouse sobre a tarefa Hash Match (Aggregate), também vejo que o SQL Server está agregando o índice de armazenamento de colunas usando o modo Batch (embora o próprio operador represente uma porcentagem tão pequena do custo da consulta). Finalmente, você Pode estar perguntando, quotOK, então o SQL Server comprime os valores nos dados, trata os valores como vetores e lê-los em blocos de quase mil valores em paralelo, mas minha consulta só queria dados para 2009. Portanto, o SQL Server está escaneando o Conjunto completo de dados. Mais uma vez, uma boa pergunta. A resposta é, quase não. Felizmente para nós, o novo pool de buffer de índice de colunas executa outra função chamada quotsegment eliminationquot. Basicamente, o SQL Server examinará os valores vetoriais da coluna da chave da data no índice do armazenamento de colunas e eliminará os segmentos que estão fora do escopo do ano de 2009. I39ll pararão aqui. Nas postagens de blog subseqüentes, eu abrico tanto o índice de armazenamento de colunas quanto o Query Store com mais detalhes. Essencialmente, o que vimos aqui hoje é que o índice Columnstore pode acelerar significativamente as consultas que exploram em grande quantidade de dados e a Query Store irá capturar execuções de consultas e nos permitir examinar as estatísticas de execução e desempenho mais tarde. No final, gostaríamos de produzir um conjunto de resultados que mostra o seguinte. Observe três coisas: as colunas rotulam essencialmente todos os possíveis Razões de retorno, depois de mostrar o valor das vendas. O conjunto de resultados contém subtotais na semana (Domingo) em todos os clientes (onde o Cliente é Nulo). O conjunto de resultados contém um total geral Linha (onde o Cliente e a Data são ambos NULL) Primeiro, antes de entrar no fim do SQL, poderíamos usar a capacidade de pivô dinâmico dinâmico no SSRS. Nós simplesmente precisamos combinar os dois conjuntos de resultados por uma coluna e então poderemos alimentar os resultados para o controle da matriz SSRS, que irá espalhar os motivos de retorno no eixo das colunas do relatório. No entanto, nem todos usam SSRS (embora a maioria das pessoas deveria). Mas, mesmo assim, às vezes, os desenvolvedores precisam consumir conjuntos de resultados em algo diferente de uma ferramenta de relatórios. Então, para este exemplo, vamos assumir que queremos gerar o conjunto de resultados para uma página de grade da web e, possivelmente, o desenvolvedor quer quotst out outar as linhas do subtotal (onde eu tenho um valor ResultSetNum de 2 e 3) e colocá-los em uma grade de resumo. Então, a linha inferior, precisamos gerar a saída acima diretamente de um procedimento armazenado. E como um toque adicional na próxima semana, poderia haver Return Raison X e Y e Z. Então, não sabemos quantos motivos de retorno podem existir. Nós simplesmente queremos que a consulta pivote sobre os possíveis valores distintos para Return Rason. Aqui é onde o PIVOT T-SQL tem uma restrição que precisamos fornecer os valores possíveis. Uma vez que ganhamos, sabemos que até o tempo de execução, precisamos gerar a seqüência de consulta dinamicamente usando o padrão SQL dinâmico. O padrão SQL dinâmico envolve a geração da sintaxe, peça por peça, armazenando-a em uma string e, em seguida, executando a string no final. SQL dinâmico pode ser complicado, pois temos que incorporar sintaxe dentro de uma string. Mas neste caso, é nossa única opção verdadeira se quisermos lidar com um número variável de razões de retorno. Eu sempre achei que a melhor maneira de criar uma solução SQL dinâmica é descobrir o que a consulta gerada quotidealquot seria no final (neste caso, dados os motivos de Retorno que conhecemos). E, em seguida, englobá-la de modo inverso Juntamente, uma parte por vez. E então, aqui é o SQL que precisamos se soubéssemos que os Razões de Retorno (A a D) eram estáticas e não mudariam. A consulta faz o seguinte: Combina os dados do SalesData com os dados de ReturnData, onde fazemos quot-wirequot a palavra Vendas como um Tipo de Ação da Tabela de Vendas e, em seguida, usamos o Razão de Retorno dos Dados de Retorno na mesma coluna do ActionType. Isso nos dará uma coluna ActionType limpa sobre a qual podermos girar. Estamos combinando as duas instruções SELECT em uma expressão de tabela comum (CTE), que é basicamente uma subconsulta de tabela derivada que posteriormente usamos na próxima declaração (para PIVOT) Uma declaração PIVOT contra o CTE, que resume os dólares para o Tipo de Ação Estar em um dos possíveis valores do tipo de ação. Observe que este não é o conjunto de resultados final. Estamos colocando isso em um CTE que lê do primeiro CTE. A razão para isso é porque queremos fazer vários agrupamentos no final. A declaração SELECT final, que lê a partir do PIVOTCTE e combina-a com uma consulta subseqüente contra o mesmo PIVOTCTE, mas onde também implementamos dois agrupamentos no recurso GROUPING SETS no SQL 2008: GROUPING by Week Week (dbo. WeekEndingDate) GRUPO para todas as linhas () Então, se soubéssemos com certeza que nunca tivemos mais códigos de razão de retorno, então essa seria a solução. No entanto, precisamos contabilizar outros códigos de razão. Portanto, precisamos gerar toda essa consulta acima como uma grande cadeia onde construímos os possíveis motivos de retorno como uma lista separada por vírgulas. I39m vai mostrar todo o código T-SQL para gerar (e executar) a consulta desejada. E então eu vou dividi-lo em partes e explicar cada passo. Então, primeiro, aqui o código inteiro para gerar dinamicamente o que eu tenho acima. Existem basicamente cinco etapas que precisamos cobrir. Passo 1 . Nós sabemos que em algum lugar da mistura, precisamos gerar uma string para isso na consulta: SalesAmount, Razão A, Razão B, Razão C, Razão D0160016001600160 O que podemos fazer é criar uma expressão de tabela comum temporária que combina as quotSales com fio rígido Montante da coluna com a lista única de possíveis códigos de razão. Uma vez que temos isso em um CTE, podemos usar o pequeno truque de FOR XML PATH (3939) para colapsar essas linhas em uma única seqüência de caracteres, colocar uma vírsa na frente de cada linha que a consulta lê e usar STUFF para substituir A primeira instância de uma vírgula com espaço vazio. Este é um truque que você pode encontrar em centenas de blogs SQL. Então, esta primeira parte cria uma string chamada ActionString que podemos usar mais abaixo. Passo 2 . Nós também sabemos que queremos somar as colunas de motivo geradas, juntamente com a coluna de vendas padrão. Então, precisamos de uma string separada para isso, que eu chamarei de SUMSTRING. Eu simplesmente usarei o ActionString original e, em seguida, REPLACE os suportes externos com a sintaxe SUM, mais os suportes originais. Passo 3: agora o trabalho real começa. Usando essa consulta original como modelo, queremos gerar a consulta original (começando com o UNION das duas tabelas), mas substituindo quaisquer referências a colunas giratórias com as strings que geramos dinamicamente acima. Além disso, embora não seja absolutamente necessário, I39 também criou uma variável para simplesmente qualquer combinação de feed de retorno de carro que queremos inserir na consulta gerada (para legibilidade). Então, construamos toda a consulta em uma variável chamada SQLPivotQuery. Passo 4. Continuamos construindo a consulta novamente, concatenando a sintaxe, podemos quotar-wirequot com ActionSelectString (que geramos dinamicamente para manter todos os possíveis valores de razão de retorno) Etapa 5. Finalmente, nós geramos a parte final do Pivot Query, que lê a partir da 2ª expressão da tabela comum (PIVOTCTE, do modelo acima) e gera o SELECT final para ler do PIVOTCTE e combiná-lo com uma 2ª leitura contra o PIVOTCTE para Implementar os conjuntos de agrupamento. Finalmente, podemos citarxecutequot a string usando o processo SQL armazenado spexecuteSQL. Então, espero que você possa ver que o processo a seguir para este tipo de esforço é Determinar qual seria a consulta final, com base em seu conjunto atual de dados e valores (isto é, construído Um modelo de consulta) Escreva o código T-SQL necessário para gerar esse modelo de consulta como uma string. Provavelmente, a parte mais importante é determinar o conjunto único de valores em que você PENSA, e depois colapsá-los em uma seqüência usando a função STUFF e o trilho FOR XML PATH (3939) Então, o que está em minha mente hoje Bem, pelo menos, 13 itens Dois No verão, escrevi um rascunho BDR que enfoca (em parte) o papel da educação e o valor de uma boa base de artes liberais, não apenas para a indústria de software, mas também para outras indústrias. Um dos temas deste BDR especial enfatizou um ponto de vista fundamental e iluminado do renomado arquiteto de software Allen Holub sobre artes liberais. (Fielmente) parafraseando sua mensagem: ele destacou os paralelos entre a programação e o estudo da história, lembrando a todos que a história está lendo e escrevendo (e eu somo, identificando padrões) e o desenvolvimento de software também está lendo e escrevendo (e novamente, identificando padrões ). E então escrevi uma peça de opinião focada neste e em outros tópicos relacionados. Mas até hoje, nunca cheguei a publicar nem publicar. De vez em quando, penso em revisá-lo, e até mesmo me sentar por alguns minutos e fazer alguns ajustes. Mas então a vida em geral iria entrar no caminho e eu nunca terminaria. Então, o que mudou Algumas semanas atrás, o colecionador CoDe Magazine e o líder da indústria, Ted Neward, escreveram uma peça em sua coluna regular, Managed Coder, que chamou minha atenção. O título do artigo é On Liberal Arts. E eu recomendo que todos leu. Ted discute o valor de um fundo de artes liberais, a falsa dicotomia entre um fundo de artes liberais e o sucesso no desenvolvimento de software, e a necessidade de escrever se comunicar bem. Ele fala sobre alguns de seus encontros anteriores com o gerenciamento de pessoal de RH em relação aos seus antecedentes educacionais. Ele também enfatiza a necessidade de aceitar e adaptar-se às mudanças em nossa indústria, bem como as características de um profissional de software bem-sucedido (ser confiável, planejar com antecedência e aprender a superar os conflitos iniciais com outros membros da equipe). Então, é uma ótima leitura, assim como os outros artigos CoDe de Teds e entradas de blog. Também me trouxe de volta a pensar em minhas opiniões sobre isso (e outros tópicos), e finalmente me motivou a terminar meu próprio editorial. Então, melhor tarde do que nunca, aqui estão os meus Bakers Dozen of Reflections: eu tenho um ditado: a água congela a 32 graus. Se você estiver em um papel de treinamento, você pode pensar que você está fazendo tudo no mundo para ajudar alguém quando de fato, eles só sentem uma temperatura de 34 graus e, portanto, as coisas não estão solidificando para eles. Às vezes é preciso apenas um pouco mais de esforço ou outro catalisador idequímico ou uma nova perspectiva, o que significa que aqueles com educação prévia podem recorrer a diferentes fontes. A água congela a 32 graus. Algumas pessoas podem manter altos níveis de concentração mesmo com uma sala cheia de gente barulhenta. Eu não sou um ocasionalmente eu preciso de alguma privacidade para pensar em um problema crítico. Algumas pessoas descrevem isso porque você deve aprender a se afastar disso. Dito de outra forma, é uma busca pelo ar rarefeito. Na semana passada, passei horas em quarto meio iluminado e silencioso com um quadro branco, até entender completamente um problema. Foi só então que eu poderia falar com outros desenvolvedores sobre uma solução. A mensagem aqui não é para pregar como você deve seguir seu negócio de resolver problemas, mas sim para que todos saibam seus pontos fortes e o que funciona e use-os em sua vantagem tanto quanto possível. Algumas frases são como as unhas em um quadro para mim. Use-o como um momento de ensino é um. (Por que é como as unhas em um quadro-negro Porque, se você estiver em um papel de mentor, você geralmente deve estar no modo de momento de ensino de qualquer maneira, por mais sutil que seja). Por outro lado, não posso realmente explicar isso em palavras, mas entendo. Isso pode soar um pouco frio, mas se uma pessoa realmente não pode explicar algo em palavras, talvez eles não entendam. Claro, uma pessoa pode ter uma sensação difusa de como algo funciona, eu posso explodir meu caminho através da descrição de como uma câmera digital funciona, mas a verdade é que eu realmente não entendo tudo tão bem. Existe um campo de estudo conhecido como epistemologia (o estudo do conhecimento). Uma das bases fundamentais para entender se é uma câmera ou um padrão de design - é a capacidade de estabelecer o contexto, identificar a cadeia de eventos relacionados, os atributos de qualquer componente ao longo do caminho, etc. Sim, a compreensão às vezes é um trabalho muito difícil , Mas mergulhar em um tópico e separá-lo vale o esforço. Mesmo aqueles que evitam a certificação reconhecerão que o processo de estudo para testes de certificação ajudará a preencher lacunas no conhecimento. Um gerenciador de banco de dados é mais provável contratar um desenvolvedor de banco de dados que possa falar extemporaneamente (e sem esforço) sobre os níveis de isolamento de transações e desencadeia, em oposição a alguém que sabe disso, mas se esforça para descrever seu uso. Há outro corolário aqui. Ted Neward recomenda que os desenvolvedores ocupem discursos em público, blogueiros, etc. Eu concordo 100. O processo de falar em público e blogging praticamente o forçará a começar a pensar em tópicos e a quebrar as definições que você poderia ter dado por certo. Há alguns anos pensei ter entendido a afirmação T-SQL MERGE muito bem. Mas apenas depois de escrever sobre isso, falando sobre, colocando perguntas de outros que tiveram perspectivas que nunca me ocorreram que meu nível de compreensão aumentou exponencialmente. Conheço uma história de gerente de contratação que já entrevistou um autordeveloper para um cargo contratado. O gerente de contratação era desdenhoso de publicações em geral e atirava o candidato, então, se você estiver trabalhando aqui, preferiria estar escrevendo livros ou escrevendo código. Sim, eu concedo que em qualquer setor haverá alguns acadêmicos puros. Mas o que o gerente de contratação perdeu foi a oportunidade de fortalecer e aprimorar os conjuntos de habilidades. Ao limpar uma velha caixa de livros, encontrei um tesouro da década de 1980: programadores no trabalho. Que contém entrevistas com um jovem Bill Gates, Ray Ozzie e outros nomes bem conhecidos. Toda entrevista e cada visão vale o preço do livro. Na minha opinião, a entrevista mais interessante foi com Butler Lampson. Que deu alguns conselhos poderosos. Para o inferno com a alfabetização informática. É absolutamente ridículo. Estudar matematica. Aprenda a pensar. Ler. Escreva. Essas coisas são de valor mais duradouro. Saiba como provar teoremas: muita evidência se acumulou ao longo dos séculos que sugere que essa habilidade é transferível para muitas outras coisas. Butler fala a verdade. Acréscimo a esse ponto, aprenda como jogar os demônios defendem contra si mesmos. Quanto mais você puder ver a realidade, verifique seus próprios processos e trabalhe, melhor será. O grande computador scientistauthor Allen Holub fez a conexão entre o desenvolvimento de software e as artes liberais especificamente, o assunto da história. Aqui estava o seu ponto de vista: o que é história Lendo e escrevendo. O que é desenvolvimento de software Entre outras coisas, leitura e escrita. Eu costumava dar a meus alunos perguntas de ensaio T-SQL como testes práticos. Um estudante brincou que eu atuei mais como um professor de direito. Bem, assim como o treinador Donny Haskins disse no filme Glory Road, meu caminho é difícil. Eu acredito firmemente em uma forte base intelectual para qualquer profissão. Assim como as aplicações podem se beneficiar de estruturas, os indivíduos e seus processos de pensamento também podem se beneficiar de estruturas humanas. Essa é a base fundamental da bolsa de estudos. Há uma história que, na década de 1970, a IBM expandiu seus esforços de recrutamento nas principais universidades, concentrando-se nos melhores e mais brilhantes graduados de artes liberais. Mesmo assim, reconheceram que os melhores leitores e escritores podem algum dia se tornar fortes analistas de sistemas programáticos. (Sinta-se livre para usar essa história para qualquer tipo de RH que insista que um candidato deve ter um diploma de ciência da computação) E falando de história: se por nenhum outro motivo, é importante lembrar o histórico de lançamentos de produtos se eu estiver trabalhando em um Site cliente que ainda está usando SQL Server 2008 ou mesmo (gasp) SQL Server 2005, eu tenho que lembrar quais recursos foram implementados nas versões ao longo do tempo. Já tem um médico favorito que você gostou porque ele explicou coisas em inglês simples, deu-lhe a verdade direta e ganhou sua confiança para operar com você. Essas são habilidades loucas. E são o resultado de experiências e TRABALHOS DUROS que levam anos e até décadas a cultivar. Não há garantias sobre o foco no sucesso do trabalho nos fatos, tire alguns riscos calculados quando tiver certeza de que pode ver o seu caminho até a linha de chegada, deixar as fichas cair onde elas podem, e nunca perder de vista ser como aquele médico que ganhou sua confiança. Mesmo que alguns dias eu fiquei curto, eu tento tratar meu cliente e seus dados como um médico trataria os pacientes. Mesmo que um médico ganhe mais dinheiro Existem muitos clichês que eu detesto, mas heres, eu não odeio: não existe uma pergunta ruim. Como ex-instrutor, uma coisa que atraiu minha ira era ouvir alguém criticar outra pessoa por ter feito uma pergunta suposta e estúpida. Uma pergunta indica que uma pessoa reconhece que eles têm alguma lacuna no conhecimento que estão procurando preencher. Sim, algumas perguntas são melhor formuladas do que outras, e algumas questões requerem enquadramento adicional antes de serem respondidas. Mas a jornada de formar uma pergunta para uma resposta provavelmente gerará um processo mental ativo em outros. Há todas as coisas boas. Muitas discussões boas e frutíferas se originam com uma pergunta estúpida. Eu trabalho em todas as ferramentas no SSIS, SSAS, SSRS, MDX, PPS, SharePoint, Power BI, DAX todas as ferramentas na pilha de BI da Microsoft. Ainda escrevo algum código. NET de vez em quando. Mas adivinhe o que ainda gasto tanto tempo escrevendo código T-SQL para dados de perfil como parte do processo de descoberta. Todos os desenvolvedores de aplicativos devem ter bons cortes T-SQL. Ted Neward escreve (corretamente) sobre a necessidade de se adaptar às mudanças de tecnologia. Acréscimo a isso a necessidade de me adaptar às mudanças do cliente. As empresas mudam as regras de negócios. As empresas adquirem outras empresas (ou se tornam alvo de uma aquisição). As empresas cometem erros na comunicação de requisitos e especificações comerciais. Sim, às vezes podemos desempenhar um papel em ajudar a gerenciar essas mudanças e, às vezes, eram a mosca, não o pára-brisa. Isso às vezes causa grande dor para todos, especialmente o I. T. pessoas. É por isso que o termo "fato da vida" existe, temos de lidar com isso. Assim como nenhum desenvolvedor escreve código sem erros sempre, não I. T. A pessoa lida bem com as mudanças a cada momento. Uma das maiores lutas que eu tive nos meus 28 anos nesta indústria está mostrando paciência e restrição quando as mudanças estão voando de muitas direções diferentes. Aqui é onde minha sugestão anterior sobre como procurar o ar rarizado pode ajudar. Se você consegue assimilar as mudanças em seu processo de pensamento e, sem se sentir sobrecarregado, as chances são de você ser um ativo significativo. Nos últimos 15 meses, tive que lidar com uma grande quantidade de mudanças profissionais. Tem sido muito difícil às vezes, mas eu decidi que a mudança será a norma e eu tentei ajustar meus próprios hábitos do melhor jeito para lidar com mudanças freqüentes (e incertas). É difícil, muito difícil. Mas como o treinador Jimmy Duggan disse no filme A League of Own: Claro que é difícil. Se não fosse difícil, todos iriam fazê-lo. O difícil, é o que o torna ótimo. Uma mensagem poderosa. Havia conversas na indústria nos últimos anos sobre a conduta em conferências profissionais (e a conduta na indústria como um todo). Muitos escritores respeitados escreveram muito bons editoriais sobre o assunto. É minha contribuição, para o que vale a pena. Its a message to those individuals who have chosen to behave badly: Dude, it shouldnt be that hard to behave like an adult. A few years ago, CoDe Magazine Chief Editor Rod Paddock made some great points in an editorial about Codes of Conduct at conferences. Its definitely unfortunate to have to remind people of what they should expect out of themselves. But the problems go deeper. A few years ago I sat on a five-person panel (3 women, 2 men) at a community event on Women in Technology. The other male stated that men succeed in this industry because the Y chromosome gives men an advantage in areas of performance. The individual who made these remarks is a highly respected technology expert, and not some bozo making dongle remarks at a conference or sponsoring a programming contest where first prize is a date with a bikini model. Our world is becoming increasingly polarized (just watch the news for five minutes), sadly with emotion often winning over reason. Even in our industry, recently I heard someone in a position of responsibility bash software tool XYZ based on a ridiculous premise and then give false praise to a competing tool. So many opinions, so many arguments, but heres the key: before taking a stand, do your homework and get the facts . Sometimes both sides are partly rightor wrong. Theres only one way to determine: get the facts. As Robert Heinlein wrote, Facts are your single clue get the facts Of course, once you get the facts, the next step is to express them in a meaningful and even compelling way. Theres nothing wrong with using some emotion in an intellectual debate but it IS wrong to replace an intellectual debate with emotion and false agenda. A while back I faced resistance to SQL Server Analysis Services from someone who claimed the tool couldnt do feature XYZ. The specifics of XYZ dont matter here. I spent about two hours that evening working up a demo to cogently demonstrate the original claim was false. In that example, it worked. I cant swear it will always work, but to me thats the only way. Im old enough to remember life at a teen in the 1970s. Back then, when a person lost hisher job, (often) it was because the person just wasnt cutting the mustard. Fast-forward to today: a sad fact of life is that even talented people are now losing their jobs because of the changing economic conditions. Theres never a full-proof method for immunity, but now more than ever its critical to provide a high level of what I call the Three Vs (value, versatility, and velocity) for your employerclients. I might not always like working weekends or very late at night to do the proverbial work of two people but then I remember there are folks out there who would give anything to be working at 1 AM at night to feed their families and pay their bills. Always be yourselfyour BEST self. Some people need inspiration from time to time. Heres mine: the great sports movie, Glory Road. If youve never watched it, and even if youre not a sports fan I can almost guarantee youll be moved like never before. And Ill close with this. If you need some major motivation, Ill refer to a story from 2006. Jason McElwain, a high school student with autism, came off the bench to score twenty points in a high school basketball game in Rochester New York. Heres a great YouTube video. His mother said it all . This is the first moment Jason has ever succeeded and is proud of himself. I look at autism as the Berlin Wall. He cracked it. To anyone who wanted to attend my session at todays SQL Saturday event in DC I apologize that the session had to be cancelled. I hate to make excuses, but a combination of getting back late from Detroit (client trip), a car thats dead (blown head gasket), and some sudden health issues with my wife have made it impossible for me to attend. Back in August, I did the same session (ColumnStore Index) for PASS as a webinar. You can go to this link to access the video (itll be streamed, as all PASS videos are streamed) The link does require that you fill out your name and email address, but thats it. And then you can watch the video. Feel free to contact me if you have questions, at kgoffkevinsgoff. net November 15, 2013 Getting started with Windows Azure and creating SQL Databases in the cloud can be a bit daunting, especially if youve never tried out any of Microsofts cloud offerings. Fortunately, Ive created a webcast to help people get started. This is an absolute beginners guide to creating SQL Databases under Windows Azure. It assumes zero prior knowledge of Azure. You can go to the BDBI Webcasts of this website and check out my webcast (dated 11102013). Or you can just download the webcast videos right here: here is part 1 and here is part 2. You can also download the slide deck here. November 03, 2013 Topic this week: SQL Server Snapshot Isolation Levels, added in SQL Server 2005. To this day, there are still many SQL developers, many good SQL developers who either arent aware of this feature, or havent had time to look at it. Hopefully this information will help. Companion webcast will be uploaded in the next day look for it in the BDBI Webcasts section of this blog. October 26, 2013 Im going to start a weekly post of T-SQL tips, covering many different versions of SQL Server over the years Heres a challenge many developers face. Ill whittle it down to a very simple example, but one where the pattern applies to many situations. Suppose you have a stored procedure that receives a single vendor ID and updates the freight for all orders with that vendor id. create procedure dbo. UpdateVendorOrders update Purchasing. PurchaseOrderHeader set Freight Freight 1 where VendorID VendorID Now, suppose we need to run this for a set of vendor IDs. Today we might run it for three vendors, tomorrow for five vendors, the next day for 100 vendors. We want to pass in the vendor IDs. If youve worked with SQL Server, you can probably guess where Im going with this. The big question is how do we pass a variable number of Vendor IDs Or, stated more generally, how do we pass an array, or a table of keys, to a procedure Something along the lines of exec dbo. UpdateVendorOrders SomeListOfVendors Over the years, developers have come up with different methods: Going all the way back to SQL Server 2000, developers might create a comma-separated list of vendor keys, and pass the CSV list as a varchar to the procedure. The procedure would shred the CSV varchar variable into a table variable and then join the PurchaseOrderHeader table to that table variable (to update the Freight for just those vendors in the table). I wrote about this in CoDe Magazine back in early 2005 (code-magazinearticleprint. aspxquickid0503071ampprintmodetrue. Tip 3) In SQL Server 2005, you could actually create an XML string of the vendor IDs, pass the XML string to the procedure, and then use XQUERY to shred the XML as a table variable. I also wrote about this in CoDe Magazine back in 2007 (code-magazinearticleprint. aspxquickid0703041ampprintmodetrue. Tip 12)Also, some developers will populate a temp table ahead of time, and then reference the temp table inside the procedure. All of these certainly work, and developers have had to use these techniques before because for years there was NO WAY to directly pass a table to a SQL Server stored procedure. Until SQL Server 2008 when Microsoft implemented the table type. This FINALLY allowed developers to pass an actual table of rows to a stored procedure. Now, it does require a few steps. We cant just pass any old table to a procedure. It has to be a pre-defined type (a template). So lets suppose we always want to pass a set of integer keys to different procedures. One day it might be a list of vendor keys. Next day it might be a list of customer keys. So we can create a generic table type of keys, one that can be instantiated for customer keys, vendor keys, etc. CREATE TYPE IntKeysTT AS TABLE ( IntKey int NOT NULL ) So Ive created a Table Typecalled IntKeysTT . Its defined to have one column an IntKey. Nowsuppose I want to load it with Vendors who have a Credit Rating of 1..and then take that list of Vendor keys and pass it to a procedure: DECLARE VendorList IntKeysTT INSERT INTO VendorList SELECT BusinessEntityID from Purchasing. Vendor WHERE CreditRating 1 So, I now have a table type variable not just any table variable, but a table type variable (that I populated the same way I would populate a normal table variable). Its in server memory (unless it needs to spill to tempDB) and is therefore private to the connectionprocess. OK, can I pass it to the stored procedure now Well, not yet we need to modify the procedure to receive a table type. Heres the code: create procedure dbo. UpdateVendorOrdersFromTT IntKeysTT IntKeysTT READONLY update Purchasing. PurchaseOrderHeader set Freight Freight 1 FROM Purchasing. PurchaseOrderHeader JOIN IntKeysTT TempVendorList ON PurchaseOrderHeader. VendorID Te mpVendorList. IntKey Notice how the procedure receives the IntKeysTT table type as a Table Type (again, not just a regular table, but a table type). It also receives it as a READONLY parameter. You CANNOT modify the contents of this table type inside the procedure. Usually you wont want to you simply want to read from it. Well, now you can reference the table type as a parameter and then utilize it in the JOIN statement, as you would any other table variable. So there you have it. A bit of work to set up the table type, but in my view, definitely worth it. Additionally, if you pass values from. NET, youre in luck. You can pass an ADO. NET data table (with the same tablename property as the name of the Table Type) to the procedure. For. NET developers who have had to pass CSV lists, XML strings, etc. to a procedure in the past, this is a huge benefit. Finally I want to talk about another approach people have used over the years. SQL Server Cursors. At the risk of sounding dogmatic, I strongly advise against Cursors, unless there is just no other way. Cursors are expensive operations in the server, For instance, someone might use a cursor approach and implement the solution this way: DECLARE VendorID int DECLARE dbcursor CURSOR FASTFORWARD FOR SELECT BusinessEntityID from Purchasing. Vendor where CreditRating 1 FETCH NEXT FROM dbcursor INTO VendorID WHILE FETCHSTATUS 0 EXEC dbo. UpdateVendorOrders VendorID FETCH NEXT FROM dbcursor INTO VendorID The best thing Ill say about this is that it works. And yes, getting something to work is a milestone. But getting something to work and getting something to work acceptably are two different things. Even if this process only takes 5-10 seconds to run, in those 5-10 seconds the cursor utilizes SQL Server resources quite heavily. Thats not a good idea in a large production environment. Additionally, the more the of rows in the cursor to fetch and the more the number of executions of the procedure, the slower it will be. When I ran both processes (the cursor approach and then the table type approach) against a small sampling of vendors (5 vendors), the processing times where 260 ms and 60 ms, respectively. So the table type approach was roughly 4 times faster. But then when I ran the 2 scenarios against a much larger of vendors (84 vendors), the different was staggering 6701 ms versus 207 ms, respectively. So the table type approach was roughly 32 times faster. Again, the CURSOR approach is definitely the least attractive approach. Even in SQL Server 2005, it would have been better to create a CSV list or an XML string (providing the number of keys could be stored in a scalar variable). But now that there is a Table Type feature in SQL Server 2008, you can achieve the objective with a feature thats more closely modeled to the way developers are thinking specifically, how do we pass a table to a procedure Now we have an answer Hope you find this feature help. Feel free to post a comment. Using Microsoft Excel to Retrieve SSAS Tabular Data Robert Sheldon Until recently, most of the talk about tabular data revolved around PowerPivot, an Excel add-in that brings powerful in-memory data crunching to the spreadsheet environment. Creating a tabular database in PowerPivot, and by extension, within Excel, is a fairly prescribed process that involves retrieving data from one or more data sources-most notably SQL Server databases-and creating one or more tables based on that data. Despite all the attention paid to PowerPivot and its tabular databases, there has been relatively little focus on how to retrieve tabular data directly from a SQL Server Analysis Services (SSAS) instance into Excel, whether through PowerPivot or directly into a workbook. In this article, we explore how to use Excel to view and retrieve data from an SSAS tabular database. This is the third article in a series about SSAS tabular data. In the last article, 8220Using DAX to retrieve tabular data ,8221 we discussed how to create Data Analysis Expressions (DAX) statements to retrieve tabular data, working from within SQL Server Management Studio (SSMS) to run our queries against an SSAS tabular instance. Some of what was covered in that article will apply to retrieving data from within Excel. For this article, I provide a number of examples of how to import tabular data into Excel. The examples pull data from the AdventureWorks Tabular Model SQL 2012 database, available as a SQL Server Data Tools (SSDT) tabular project from the AdventureWorks CodePlex site. On my system, I8217ve implemented the database on a local instance of SSAS 2012 in tabular mode. Viewing Browsed Data in Excel We got a taste of how to browse data from within SSMS in the first article of this series, 8220Getting Started with the SSAS Tabular Model .8221 In Object Explorer. right-click the database and then click Browse. When the Browse window appears, you can view a list of database objects and use those objects to retrieve data by dragging them into the main workspace. For example, Figure 1 shows data from the Country Region Name and City columns of the Geography table, as well as from the Internet Total Sales and Internet Total Units measures of the Internet Sales table. Figure 1: Browsing tabular data in SSMS Notice in Figure 1 that I also created a filter that limits the amount of data returned. (You define filters in the small windows above the main workspace.) In this case, I eliminated all sales that include the value Bikes in the Category Name column of the Product table. This way, all non-bike merchandise is included in the sales figures. What8217s shown in Figure 1 is pretty much the extent of what you can do in the Browse window in SSMS. To be able to fully drill into the data, you need to use Excel. Starting with SQL Server 2012, Excel is now the de facto tool in SSMS and SSDT for analyzing tabular data. Unfortunately, that means you need Office 2003 or later installed on the same computer where SSMS and SSDT are installed, not a practical solution for everyone. Even so, having Excel installed makes analyzing tabular data a much easier process. Part of that simplicity lies in the fact that the SSMS Browse window and the SSDT tabular project window both include the Analyze in Excel button on their respective menus. The button launches Excel and let8217s you browse the tabular data from within in a pivot table. When you first click the Analyze in Excel button, you must choose which perspective to open in Excel, as shown in Figure 2. As you might recall from the first article, a perspective represents all or part of the data model. The Model perspective includes all database components. Figure 2: Selecting a perspective when sending data to Excel Once you8217ve selected a perspective, click OK. Excel is launched and opens to a new pivot table that automatically connects to the SSAS tabular data source. Figure 3 shows the pivot table before any data has been added. Notice in the right window you8217ll find the PivotTable Field List pane, which contains a list of all your database objects, including tables, columns, and measures. Figure 3: Importing tabular data into an Excel pivot table To get started with the pivot table, drag the fields and measures you want to include in your report to the Column Labels. Row Labels. and Values panes. The data will then be displayed in the pivot table. You can also create filters by dragging fields to the Report Filter pane. Figure 4 shows the pivot table after I added numerous database objects. Many of these objects are the same columns and measures that were added to the Browse window shown in Figure 1, except that now I also break down the sales by years. Figure 4: Working with tabular data in an Excel pivot table To configure the pivot table shown in Figure 4, I added the following database objects to the specified configuration panes in the right window: The Country Region Name column from the Geography table to the Row Labels pane. The City column from the Geography table to the Row Labels pane. The Year column (from the Calendar hierarchy) of the Date table to the Column Labels pane. The Internet Total Sales measure from the I nternet Sales table to the Values pane. The Internet Total Units measure from the Internet Sales table to the Values pane. The Product Category Name column from the Product table to the Report Filter pane. Once you8217ve set up your pivot table, you can play around with the data however you want. For example, you can drill down into the year values or view only the country totals without viewing the cities. You can also find rollups for each category of data. Plus, you can filter data based on the values in the Product Category Name column. Keep in mind, however, that this article is by no means a tutorial on how to work with Excel pivot tables. For that, you need to check out the Excel documentation. SSMS and SSDT make it easy to view the data in Excel, but it8217s up to you to derive meaning from what you find. Importing Data into an Excel Pivot Table Not everyone will have SSMS or SSDT installed on their systems, but they might still need to access an SSAS instance to retrieve tabular data. In that case, they can establish their own connection to the tabular database (assuming they have the necessary permissions) and import the data into a pivot table, just as we saw above. To connect to a tabular database from within Excel, go to the Data tab, click the From Other Sources button, and then click From Analysis Services. When the Data Connection Wizard appears, type the instance name and any necessary logon credentials, as shown in Figure 5. (In my case, I used Windows Authentication.) Figure 5: Connecting to an SSAS instance in tabular mode Click Next to advance to the Select Database and Table page, shown in Figure 6. Here you select the database you want to connect to and the specific perspective. Once again, I8217ve selected Model in order to retrieve all the database components. (As you8217ve probably noticed, Microsoft is somewhat inconsistent in its interfaces when it comes to referring to perspectives in a tabular database. Sometimes they8217re referred to as cubes, sometimes perspective, and sometimes Model is referred to as a cube and the other components as perspectives. I8217m not sure how Table fits into the picture.) Figure 6: Selecting a perspective when connecting to tabular data After you8217ve selected your database and perspective, click Next to advance to the Save Data Connection File and Finish page, shown in Figure 7. Here you can provide a name for the data connection file (an. odc file), a description of the connection, and a friendly name for the connection. Figure 7: Creating a data connection file in Excel Once you8217ve supplied the necessary information, click Finish. You8217ll then be presented with the Import Data dialog box, as shown in Figure 8. You can choose whether to create a pivot table, a pivot table and pivot chart, or the data connection only. You can also choose to use the existing worksheet or open a new one. Figure 8: Importing tabular data into a pivot table You might have noticed that the Table option is grayed out. When importing tabular data in this way, Excel is very picky. Either you use a pivot table (and pivot chart, if you want) or nothing at all. You cannot import the data into a set of tables. However, there is a way to work around the default behavior, which we cover in the following section. But for now, stick with the default options (those shown in Figure 8), and click OK. You8217ll then be presented with a new pivot table and the PivotTable Field List pane, with all the tables and their columns and measures listed, similar to what is shown in Figure 3. You can then work with that data to create a report just like we did earlier. Using DAX to Import Data into Excel To import tabular data into a regular Excel table, rather than a pivot table, we can create a DAX expression that pulls in exactly the data we need. We start by creating a data connection, just as we did in the last section. Once again, launch the Data Connection Wizard and follow the prompts. When you get to the Save Data Connection File and Finish page, provide a file name, description, and friendly name. But keep all the names simple because we8217ll be referencing them later in the process and we want to make sure everything is easy to find. Figure 9 shows the names I used to set up the data connection on my system. Figure 9: Creating a data connection file in Excel When you click Finish. you8217ll again be presented with the Import Data dialog box. This time around, select the option Only Create Connection. as shown in Figure 10. We don8217t want to pull in any data just yet. We just want to establish how we8217ll be connecting to the tabular database. Click OK to finish creating the connection. Figure 10: Creating a data connection without creating a pivot table The next step is to locate the data connection file we just created so we can edit it. On my system, I had named the file awquery. odc. and I found it in the My DocumentsMy Data Sources folder associated with my user account. When editing the connection file, which we can do in Notepad, we want to modify the default settings so we can use a DAX query to retrieve the data. To achieve this, we need to modify two lines, the CommandType and CommandText elements, which are highlighted in the following HTML: I highlighted the new code to make it easier to pick out. I also laid out the DAX statement so it8217s more readable. However, you don8217t need to break it apart in this way to add it into the file. (The parser ignores the extra whitespace and line breaks.) After you save and close the data connection file, it8217s time to verify what you8217ve done. In Excel, go to the Data tab and click Existing Connections. When the Existing Connections dialog box appears, double-click the connection you just edited. It will be listed under its friendly name, not the file name. On my system, the connection8217s friendly name is AdventureWorks query. This launches the Import Data dialog box, shown in Figure 11. Notice that this time around, the Table option is available and selected. Figure 11: Importing tabular data into an Excel table Click OK to close the Import Data dialog box. A table will appear, populated with the data retrieved through the DAX statement, as shown in Figure 11. You can then sort through the data and create any necessary filters. Figure 12: Working with tabular data in an Excel table When you8217re working in a table based on tabular data, you can modify the connection associated with the current workbook. Doing so, however, severs its relationship to the original. odc data connection file. Instead, your changes are saved to the connection specifically associated with that workbook. The. odc file remains unchanged. Updating the connection in this way lets you modify the DAX statement, change the connection string, or configure other properties. To modify the workbook8217s connection, go to the Data tab and click Connections. This launches the Workbook Connections dialog box, shown in Figure 13. Here you should find the connection you created earlier. On my system, this is AdventureWorks query. Figure 13: Viewing the data connections associated with an Excel workbook Next, we want to access the connection8217s properties. Make sure the connection is selected (in case you have more than one connection listed), and then click Properties. This launches the Connection Properties dialog box. Go to the Definition tab and expand the dialog box as necessary to easily view the DAX statement. Figure 14 shows what the dialog box looks like on my system. Figure 14: Viewing the properties of an Excel data connection Chances are, when you open the dialog box, the DAX statement will be difficult to read. The statement shown in Figure 14 is what it looked like after I organized things a bit for readability. The changes I made have no impact on the statement itself. You can modify the DAX statement or connection string as necessary (or any other properties, for that matter). To save you changes, click OK. You8217ll then be presented with an Excel message box warning you that you are about to sever ties with the original data connection file, as shown in Figure 15. That8217s not a problem, though, because your updated connection information will be saved with the workbook when you save it. Figure 15: Severing ties between a data connection and its source file You can now update you connection as often as you like. You should not receive this warning going forward. You can also use the existing. odc connection to easily add other tables to your workbook. To do so, add a new worksheet, connect to the data source via the. odc connection, and then modify the connection properties by adding a different DAX statement. (You can also rename the connection as necessary.) That way you can create a workbook that contains numerous worksheets that each includes an imported table from a tabular data source. Using DAX to Import Data into PowerPivot Up to this point, I8217ve shied away from discussing PowerPivot in too great of detail, mostly because it8217s already received so much press. But one issue that8217s received little attention is how you retrieve data from an SSAS tabular instance into PowerPivot. Surprisingly, the functionality is somewhat limited. You would expect-or at least I would expect-that I could import all the tables, along with their columns and measures, in a single connection, just as I can do with an Excel pivot table or a SQL Server database in PowerPivot. But that doesn8217t appear to be the case. The only option I can find for importing tabular data directly into PowerPivot is one table at a time, just like we saw with Excel tables. However, doing so in PowerPivot is a bit easier. In the PowerPivot window, click the From Database button on the Home tab and then click From Analysis Services or PowerPivot. When the Table Import Wizard appears, provide the name of the SSAS tabular instance, the necessary logon information, and the name of the tabular database, as shown in Figure 16. Figure 16: Defining a data connection to an SSAS tabular database Don8217t forget, you can also provide a friendly connection name. And it8217s always a good idea to test your connection. When you8217re finished, click Next . The next page in the wizard is Specify a MDX Query. As with SSMS or your Excel data connections, you can specify a DAX query rather than a Multidimensional Expressions (MDX) query. We8217ll go with DAX. Figure 17 shows the page with the same query we used in the previous section. You can use the Validate option to check your statement, which seems to work with DAX, unlike the Design option, which seems happier sticking with MDX. Figure 17: Defining a DAX query to retrieve tabular data from SSAS After you entered your DAX query (and provided a name for the query, if you like), click Finish to import the data. During this process, you8217ll advance to the wizard8217s Importing page. If the data is imported with no problems, you should receive a Success message, as shown in Figure 18. Figure 18: Successfully importing SSAS tabular data into PowerPivot for Excel Click Close. This will open a new table in the PowerPivot window, with the imported data displayed. Figure 19 shows part of the data returned by the query. If the data is not exactly what you need, you can refine your query as necessary. Figure 19: Working with tabular data in PowerPivot for Excel You can import data into as many tables as you need. You can then create relationships between those tables, assuming you bring in the columns necessary to define those relationships. Not surprisingly, it would be handier to go directly to the source of the data, in this case, the AdventureWorksDW2012 database, so you can retrieve all the tables at once, along with their defined relationships. But you might not have access to that data and have no choice but to be retrieve it directly from the SSAS instance. Or there might be other circumstances that require you to retrieve the data directly from SSAS. Whatever the reason, you now know how it8217s done, and once you8217ve tried it out, you8217ll find it8217s a fairly simple operation. The Excel Connection As you8217ve seen in this article, you have several options for retrieving SSAS tabular data into Excel. You can launch Excel from within SSMS or SSDT. You can import data directly into a pivot table. And you can generate DAX queries to retrieve data into individual Excel and PowerPivot tables. Or instead of DAX, you can generate MDX queries, unless the tabular database has been set up in DirectQuery mode. Regardless, you have a number of options for importing tabular data into Excel. And once you get it there, you have a rich environment for manipulating and analyzing the data, allowing you to create precise and detailed reports in the format you need when you need them, without having to be concerned about SSAS and how the tabular model works. Total: 28 Average: 4.35 After being dropped 35 feet from a helicopter and spending the next year recovering. Robert Sheldon left the Colorado Rockies and emergency rescue work to pursue safer and less painful intereststhus his entry into the world of technology. He is now a technical consultant and the author of numerous books, articles, and training material related to Microsoft Windows, various relational database management systems, and business intelligence design and implementation. He has also written news stories, feature articles, restaurant reviews, legal summaries, and the novels Last Stand and Dancing the River Lightly. You can find more information at rhsheldon. calculated columns Hi Robert, thanks for the very good overview of these different approaches on xls. When importing ssas tabular into an excel pivot table my calculated columns cannot be placed in the value area of the pivot table ndash only measures can be placed there. Do you have an idea whether this is a common thing or might be an error in my workbook Thanks, feldi Excel vs Power View for Data Exploration Thank you for this excellent article, Robert Irsquove read that Excel passes MDX instead of DAX queries to the tabular model. Do you think that organizations should choose Power View or Power BI instead of Excel for data exploration for this reason Thank you, Vince Good article thanks. I have a connection in Excel using DAX query. I have set the connection to refresh on opening the file. However, when I view the file on a browser, the connection does not refresh automatically. Other data connections connected to SSAS and retrieving a Pivot table do refresh automatically. Thoughts Is this not supported Join Simple Talk Join over 200,000 Microsoft professionals, and get full, free access to technical articles, our twice-monthly Simple Talk newsletter, and free SQL tools. Visite nossa biblioteca de artigos para descobrir os padrões e práticas que você precisa para avançar para métodos mais ágeis de entrega de banco de dados. Find out how to automate the process of building, testing and deploying your database changes to reduce risk and speed up the delivery cycle. Related articles Also in Database With the rise of NoSQL databases that are exploiting aspects of SQL for querying, and are embracing full transactionality, is there a danger of the data-document models hierarchical nature causing a fundamental conflict with relational theory We asked our relational expert, Hugh Bin-Haad to expound a difficult area for database theorists. hellip Read more Also in PowerPivot Data Analysis Expressions (DAX), originally the formula language for PowerPivot workbooks, can also be used within the MDX query window of SSMS to directly access data from a tabular SSAS database, an in-memory database that uses the xVelocity analytics engine and compression. Robert Sheldon shows how easy it is to retrieve data from a tabular database. hellip Read more Also in Reporting Services Whats the best way of providing self-service business intelligence (BI) to data that is held in on-premise SQL Server Not, it seems, Power BI 2.0 the hosted cloud service, but Power BI 2.0 Desktop. If moving your database to Azure isnt an option, Power BI 2.0 desktop could still bring smiles to the faces of your BI hotshots. hellip Read more Also in SQL Every SQL Server Database programmer needs to be familiar with the System Functions. These range from the sublime (such as rowcount or identity) to the ridiculous (IsNumeric()) Robert Sheldon provides an overview of the most commonly used of them. hellip Read more copy 2005 - 2017 Red Gate Software Ltd What do you think of the new Simple Talk Give us your feedback

No comments:

Post a Comment