Wednesday, 12 July 2017

Fórmula De Modelo Em Movimento


GASES, LIQUIDOS e SOLIDOS aplicação do modelo de partículas para os três estados de modelos de partículas de matéria, descrevendo, explicando as propriedades de gases, líquidos e sólidos Doc Browns Química KS4 ciência GCSEIGCSE Notas de revisão Comparação das propriedades de GASES, LIQUIDS e SOLIDS States Notas sobre a revisão de gases da matéria prima Part 1 O modelo de partículas cinéticas e descrevendo e explicando as propriedades dos gases, líquidos e sólidos, mudanças de estado e soluções (seções 1a a 3d). Você deve saber que os três estados da matéria são sólidos, líquidos e gasosos. O derretimento eo congelamento ocorrem no ponto de fusão, a ebulição e a condensação ocorrem no ponto de ebulição. Os três estados da matéria podem ser representados por um modelo simples em que as partículas são representadas por pequenas esferas sólidas. A teoria das partículas pode ajudar a explicar o derretimento, a ebulição, o congelamento e a condensação. A quantidade de energia necessária para mudar o estado do sólido para o líquido e do líquido para o gás depende da força das forças entre as partículas da substância e a natureza das partículas envolvidas depende do tipo de ligação e da estrutura da substância. Quanto mais fortes as forças entre as partículas, maior o ponto de fusão e ponto de ebulição da substância. Para detalhes veja a estrutura e as notas de ligação. Existem limitações do modelo simples, incluindo que não há forças entre as esferas e as esferas são sólidas e inelásticas, tudo falso. O estado físico que um material adota depende da sua estrutura, temperatura e pressão. Símbolos de estado utilizados nas equações: (g) gás (l) solução (s) aquosa (s) líquida (s) líquida (s) solução aquosa sólida significa algo dissolvido em água A maioria dos diagramas de partículas nesta página são representações 2D de sua estrutura e estado. EXEMPLOS DOS TRÊS FÍSICOS ESTADOS DOS GASES DE MATÉRIA, por exemplo, A mistura de ar ao nosso redor (incluindo o oxigênio necessário para a combustão) e o vapor de alta pressão na caldeira e cilindros da locomotiva a vapor. Todos os gases no ar são invisíveis, sendo incolores e transparentes. Note-se que o vapor que você vê fora de uma chaleira ou locomotiva a vapor é realmente gotículas líquidas finas de água, formadas a partir da condensação de gás de vapor expelido quando ele atende o ar frio, o estado de mudança de gás para líquido (mesmo efeito na formação de névoa e névoa) . LÍQUIDOS, e. A água é o exemplo mais comum, mas também o leite, a manteiga quente, a gasolina, o óleo, o mercúrio ou o álcool em um termômetro. SOLIDOS, e. Pedra, todos os metais à temperatura ambiente (exceto mercúrio), borracha de botas para caminhada e a maioria dos objetos físicos ao seu redor. De fato, a maioria dos objetos são inúteis a menos que tenham uma estrutura sólida. Nesta página, as propriedades físicas básicas dos gases, líquidos e sólidos são descritas em termos de estrutura, movimento de partículas (teoria da partícula cinética), efeitos de mudanças de temperatura e pressão e modelos de partículas Usado para explicar essas propriedades e características. Felizmente, a teoria e os factos coincidirão para dar aos alunos uma compreensão clara do mundo material à sua volta em termos de gases, líquidos e sólidos referidos como os três estados físicos da matéria. As mudanças de estado conhecidas como fusão, fusão, ferver, evaporar, condensar, licuar, congelar, solidificar, cristalizar são descritas e explicadas com imagens de modelo de partículas para ajudar a entender. Há também uma menção de líquidos miscíveis e imiscíveis e explicando os termos volátil e volatilidade quando aplicado a um líquido. Essas notas de revisão sobre os estados da questão devem ser úteis para os novos cursos de ciências químicas da AQA, Edexcel e OCR GCSE (91). Subíndice para seções da Parte I (esta página): 1.1. Os Três Estados da Matéria, modelos de teor de partículas de partículas de gás Os três estados da matéria são sólidos, líquidos e gasosos. Qualquer fusão e congelação podem ocorrer no ponto de fusão, enquanto que a ebulição e a condensação ocorrem no ponto de ebulição. A evaporação pode ocorrer a qualquer temperatura a partir de uma superfície líquida. Você pode representar os três estados da matéria com um modelo de partículas simples. Nestes diagramas de modelo, as partículas são representadas por pequenas esferas sólidas (a estrutura eletrônica é ignorada). A teoria da partícula cinética pode ajudar a explicar mudanças de estado como fusão, ferver, congelar e condensar. A quantidade de energia necessária para mudar o estado do sólido para o líquido ou do líquido para o gás depende da força das forças entre as partículas da substância. Essas forças podem ser forças intermoleculares relativamente fracas (ligação intermolecular) ou fortes ligações químicas (iónicas, covalentes ou metálicas). A natureza das partículas envolvidas depende do tipo de ligação química e da estrutura da substância. Quanto mais fortes forem as forças atrativas entre as partículas, maior o ponto de fusão e ponto de ebulição da substância QUAIS SÃO OS TRÊS ESTADOS DE MATÉRIA A maioria dos materiais pode ser simplesmente descrito como um gás, um líquido ou um sólido. PORQUE SÃO QUE GOSTAM O QUE SÃO Apenas sabendo que não é suficiente, precisamos de uma teoria abrangente dos gases, que podem explicar seu comportamento e fazer previsões sobre o que acontece, e. Se mudarmos a temperatura ou a pressão. COMO PODEMOS EXPLICAR COMO PERSEGUIAMOS Precisamos de um modelo teórico, e. Teoria das partículas que é apoiada por evidências experimentais. CAN MODELOS DE PARTÍCULAS AJUDAM QUE NÓS ENTENDEM SUAS PROPRIEDADES E CARACTERÍSTICAS POR QUE É IMPORTANTE SABER AS PROPRIEDADES DE GÁS, LÍQUIDOS E SÓLIDOS É importante que, na indústria química, conheça o comportamento de gases, líquidos e sólidos em processos químicos, e. O que acontece com os diferentes estados com mudanças de temperatura e pressão. O que é a TEORIA DE PARTÍCULAS CINETICAS de gases, líquidos e sólidos A teoria das partículas cinéticas dos estados da matéria baseia-se na idéia de todos os materiais existentes como partículas muito pequenas que podem ser átomos ou moléculas individuais e sua interação uns com os outros Por colisão em gases ou líquidos ou por vibração e ligação química em sólidos. PODEMOS FAZER PREDICAÇÕES COM BASE EM SUAS PROPRIEDADES CARACTERÍSTICAS Esta página apresenta descrições físicas gerais de substâncias no nível de classificação físico (não químico) mais simples, isto é, é um gás, líquido ou sólido. MAS, esta página da Web também apresenta modelos de partículas em que um pequeno círculo representa um átomo ou uma molécula, isto é, uma partícula particular ou a unidade mais simples de uma substância. Esta seção é bastante abstracta de uma maneira porque você está falando de partículas que você não pode ver como individualmente, você apenas o material a granel e seu caráter físico e suas propriedades. Existem LIMITAÇÕES ao modelo de partículas (precisa de mais) O modelo simples leva pouco em conta as forças entre as partículas. Assume que não há forças de atração entre partículas de gás, o que na verdade não é verdade, mesmo que sejam muito fracos. As partículas são tratadas como simples esferas inelásticas e apenas se comportam como bolas de snooker minúsculas voando ao redor. QUAL É O ESTADO GASESO DE MATÉRTICA QUAIS SÃO AS PROPRIEDADES DE UM GÁS COMO AS PARTÍCULAS GASESAS ESTÃO COMO COMO A TEORIA DE DIGAS CINÉMICAS DOS GÁNULOS GERA AS PROPRIEDADES DOS GASES Um gás não tem forma ou volume fixo, mas sempre se espalha para encher qualquer recipiente - As moléculas de gás se espalharão para qualquer espaço disponível. Não há quase nenhuma força de atração entre as partículas para que elas estejam completamente livres uma da outra. As partículas são amplamente espaçadas e dispersas ao se mover rapidamente ao acaso ao longo do recipiente, de modo que não há ordem no sistema. As partículas movem-se de forma linear e rápida em todas as direções. E colidem frequentemente entre si e com o lado do recipiente. A colisão de partículas de gás com a superfície de um recipiente provoca pressão de gás. Ao saltar de uma superfície, eles exercem uma força ao fazê-lo. Com o aumento da temperatura. As partículas se movem mais rápido, pois ganham energia cinética. A taxa de colisões entre as próprias partículas e a superfície do recipiente aumenta e isso aumenta a pressão do gás, por exemplo, em uma locomotiva a vapor ou o volume do recipiente, se puder expandir, por exemplo, como um balão. Os gases têm uma densidade muito baixa (luz) porque as partículas estão tão espaçadas no recipiente (volume de massa de densidade). Ordem de densidade: gases gt gt líquidos gb Os gases fluem livremente porque não existem forças efetivas de atração entre as moléculas de partículas gasosas. Facilidade de ordem de fluxo. Gases gt líquidos gtgtgt sólidos (nenhum fluxo real em sólido, a menos que você o emite) Por causa disso, esses gases e líquidos são descritos como fluidos. Os gases não têm superfície. E nenhuma forma ou volume fixo. E por falta de atração de partículas, eles sempre se espalham e enchem qualquer recipiente (por isso, volume do recipiente de volume de gás). Os gases são facilmente compactados devido ao espaço vazio entre as partículas. Facilidade de compactação. Gases gtgtgt líquidos sólidos gt (quase impossível de comprimir um sólido) Pressão do gás Quando um gás é confinado em um recipiente, as partículas causarão e exercerão uma pressão de gás que é medida em atmosferas (atm) ou Pascals (1,0 Pa 1,0 Nm 2) A pressão é a força, ou seja, o efeito de todas as colisões na superfície do recipiente. A pressão do gás é causada pela força criada por milhões de impactos das minúsculas partículas de gás individuais nos lados de um recipiente. Por exemplo, se o número de partículas gasosas em um recipiente for duplicado, a pressão do gás é dobrada porque duplicar o número de moléculas dobra o número de impactos no lado do recipiente, de modo que a força de impacto total por unidade de área também é dobrada. Essa duplicação dos impactos das partículas que duplicam a pressão é retratada nos dois diagramas abaixo. Se o volume de um recipiente selado for mantido constante e o gás interno for aquecido a uma temperatura mais alta, a pressão do gás aumenta. A razão para isso é que, à medida que as partículas são aquecidas, elas ganham energia cinética e, em média, se movem mais rapidamente. Portanto, eles colidirão com os lados do recipiente com maior força de impacto. Aumentando assim a pressão. Há também uma maior freqüência de colisão com os lados do recipiente, MAS isso é um fator menor em comparação com o efeito do aumento da energia cinética e o aumento da força média de impacto. Portanto, uma quantidade fixa de gás em um recipiente selado de volume constante, quanto maior a temperatura, maior a pressão e menor a temperatura, menor a pressão. Para os cálculos da temperatura da pressão do gás, consulte a Parte 2 Lei CharlessGayLussacs Se o volume do recipiente pode mudar, os gases ampliam rapidamente o aquecimento devido à falta de atração de partículas e se contraem prontamente ao resfriamento. Ao aquecer, as partículas de gás ganham energia cinética. Mova-se mais rápido e bata os lados do recipiente com mais freqüência. E significativamente, eles atingiram com uma força maior. Dependendo da situação do recipiente, uma ou ambas as pressões ou o volume aumentarão (inverter no resfriamento). Nota: É o volume de gás que expande NÃO as moléculas, elas permanecem do mesmo tamanho. Se não houver restrição de volume, a expansão no aquecimento é muito maior para gases do que líquidos ou sólidos porque não há atração significativa entre partículas gasosas. O aumento da energia cinética média aumentará a pressão do gás e, portanto, o gás tentará expandir-se em volume, se for permitido, p. Ex. Os balões em um quarto quente são significativamente maiores do que o mesmo balão em uma sala fria. Para os cálculos da temperatura do volume de gás, consulte a Parte 2 CharlessGayLussacs Law DIFFUSION in Gases: o movimento natural rápido e aleatório das partículas em todas as direções significa que os gases são facilmente espalhados ou difusos. O movimento líquido de um gás específico estará na direção de menor concentração até uma concentração mais alta, abaixo do gradiente de difusão denominado. Di ffusion continua até que as concentrações sejam uniformes em todo o recipiente de gases, mas TODAS as partículas continuam movendo-se com sua energia cinética sempre presente. A difusão é mais rápida nos gases do que nos líquidos, onde há mais espaço para se moverem (experimento ilustrado abaixo) e a difusão é Desprezível em sólidos devido ao fechamento das partículas. A difusão é responsável pela propagação de odores, mesmo sem qualquer perturbação do ar, p. Ex. Uso de perfume, abertura de uma jarra de café ou o cheiro de gasolina em torno de uma garagem. A taxa de difusão aumenta com o aumento de temperatura à medida que as partículas ganham energia cinética e se movem mais rapidamente. Outras evidências para o movimento de partículas aleatórias, incluindo a difusão. Quando as partículas de fumo são vistas sob um microscópio, elas parecem dançar ao redor quando iluminadas com um feixe de luz em 90 o na direção da visão. Isso ocorre porque as partículas de fumaça aparecem por luz refletida e dança devido aos milhões de acessos aleatórios das moléculas de ar em movimento rápido. Isso é chamado de movimento browniano (veja abaixo em líquidos). Em qualquer instante dado, os hits não serão iguais, então a partícula de fumaça obtém um golpe maior em uma direção aleatória. Um experimento de difusão de duas moléculas gasosas é ilustrado acima e explicado abaixo. Um tubo de vidro longo (24 cm de diâmetro) é preenchido em uma extremidade com um tampão de algodão embebido em conc. Ácido clorídrico selado com um tampão de borracha (para a saúde e segurança) eo tubo é mantido perfeitamente imóvel, apertado em posição horizontal. Um plug semelhante de conc. A solução de amônia é colocada na outra extremidade. Os tampões de lã de algodão embebidos libertarão fumos de HCl e NH3, respectivamente, e se o tubo for deixado inalterado e horizontal, apesar da falta de movimento do tubo, e. Não tremendo para misturar e a ausência de convecção, uma nuvem branca se forma cerca de 1 3 a partir do conc. Extremidade do tubo de ácido clorídrico. Explicação: o que acontece é os gases incolores, amônia e cloreto de hidrogênio, difundem pelo tubo e reagem para formar cristais brancos finos do cloreto de sal de amônio. Cloreto de hidrogénio de amônia cloreto de amónio gt NH 3 (g) HCl (g) gt NH 4 Cl (s) Observe a regra: quanto menor a massa molecular, maior a velocidade média das moléculas (mas todos os gases têm a mesma energia cinética média Na mesma temperatura). Portanto, quanto menor a massa molecular, mais rápido o gás difunde. por exemplo. M r (NH3) 14 1x3 17. Move-se mais rápido do que M r (HCl) 1 35,5 36,5 E é por isso que eles se encontram mais perto do extremo HCl do tubo. Portanto, o experimento não é apenas evidência do movimento da molécula. Também é evidência de que moléculas de diferentes massas moleculares se movimentaram a diferentes velocidades. Para um tratamento matemático, veja Grahams Law of Diffusion Um gás colorido, mais pesado que o ar (maior densidade), é colocado no recipiente de gás inferior e um segundo jarro de gás de ar incolor de densidade inferior é colocado sobre ele separado com uma cobertura de vidro. As experiências de difusão devem ser fechadas a uma temperatura constante para minimizar os distúrbios por convecção. Se a cobertura de vidro for removida, então (i) os gases do ar incolores difundem para dentro do gás marrom colorido e (ii) o brometo difunde-se no ar. O movimento aleatório das partículas que leva à mistura não pode ser devido à convecção porque o gás mais denso começa na parte inferior. Não é necessária nenhuma agitação ou outros meios de mistura. O movimento aleatório de ambos os lotes de partículas é suficiente para garantir que ambos os gases eventualmente se tornem completamente misturados por difusão (espalhados um para o outro). Esta é uma clara evidência de difusão devido ao movimento contínuo aleatório de todas as partículas de gás e, inicialmente, o movimento líquido de um tipo de partícula de uma concentração mais alta para uma menor (um gradiente de difusão). Quando totalmente misturado, nenhuma outra distribuição de mudança de cor é observada MAS o movimento aleatório de partículas continua Veja também outras evidências na seção líquida após o modelo de partículas para o diagrama de difusão abaixo. Um modelo de partículas de difusão em gases. Imagine o gradiente de difusão da esquerda para a direita para as partículas verdes adicionadas às partículas azuis à esquerda. Assim, para as partículas verdes, a migração líquida é da esquerda para a direita e continuará, em um recipiente selado, até que todas as partículas estejam distribuídas uniformemente no recipiente de gás (conforme ilustrado). A difusão é mais rápida nos gases em comparação com as soluções de líquidos porque há mais espaço entre as partículas para que outras partículas se movam ao acaso. Quando um sólido é aquecido, as partículas vibram mais fortemente à medida que ganham energia cinética e as forças atrativas de partículas estão enfraquecidas. Eventualmente, no ponto de fusão. As forças atrativas são muito fracas para manter as partículas na estrutura unidas de maneira ordenada e assim o sólido derrete. Note-se que as forças intermoleculares ainda estão lá para manter o líquido em massa juntas, mas o efeito não é suficientemente forte para formar uma rede de cristal ordenada de um sólido. As partículas tornam-se livres para se deslocar e perder o arranjo ordenado. É necessária energia para superar as forças atraentes e dar às partículas energia cinética aumentada de vibração. Portanto, o calor é absorvido pelos arredores e a fusão é um processo endotérmico (916H ve). As mudanças de energia para essas mudanças físicas de estado para uma variedade de substâncias são tratadas em uma seção das Notas Energéticas. Explicado usando a teoria das partículas cinéticas de líquidos e sólidos. No resfriamento, partículas líquidas perdem energia cinética e, portanto, podem se atrair mais fortemente umas para as outras. Quando a temperatura é suficientemente baixa, a energia cinética das partículas é insuficiente para evitar que as forças atrativas de partículas causem a formação de um sólido. Eventualmente, no ponto de congelamento, as forças de atração são suficientes para remover qualquer liberdade de movimento restante (em termos de um lugar para outro) e as partículas se juntam para formar o arranjo sólido ordenado (embora as partículas ainda tenham energia cinética vibratória. Deve ser removido para os arredores, por mais estranho que pareça, o congelamento é um processo exotérmico (916H ve). Mudanças de energia comparativa de mudanças de estado gas ltgt líquido ltgt sólido 2f (i) Curva de resfriamento. O que acontece com a temperatura de uma substância Se for arrefecido a partir do estado gasoso para o estado sólido, observe que a temperatura permanece constante durante as mudanças de estado de condensação à temperatura Tc. E solidificação de gelo na temperatura Tf. Isso ocorre porque toda a energia térmica removida ao refrigerar a essas temperaturas (as latentes funcionam Ou entalpias de mudança de estado), permite o fortalecimento das forças interpartículas (ligação intermolecular) sem queda de temperatura. A perda de calor é compensada D pela atração de força intermolecular aumentada exotérmica. Entre as seções de mudança de estado horizontal do gráfico, você pode ver a remoção de energia reduz a energia cinética das partículas, diminuindo a temperatura da substância. Consulte a seção 2. para obter uma descrição detalhada das mudanças de estado. Uma curva de resfriamento resume as mudanças: para cada mudança de estado, a energia deve ser removida. Conhecido como o calor latente. Os valores de energia real para essas mudanças físicas de estado para uma variedade de substâncias são tratados com mais detalhes nas Notas Energéticas. 2f (ii) Curva de aquecimento. O que acontece com a temperatura de uma substância se for aquecida do estado sólido ao estado gasoso. Observe que a temperatura permanece constante durante o estado de mudanças de fusão à temperatura Tm e com ponto de ebulição a temperatura Tb. Isso ocorre porque toda a energia absorvida no aquecimento a essas temperaturas (as latentes cicatrizes ou entalpias de mudança de estado), entra em debilitar as forças interpartículas (ligação intermolecular) sem elevação de temperatura. O ganho de calor é igual à energia absorvida que absorve para reduzir as forças intermoleculares . Entre as seções de mudança de estado horizontal do gráfico, você pode ver a entrada de energia aumentar a energia cinética das partículas e aumentar a temperatura da substância. Consulte a seção 2. para obter uma descrição detalhada das mudanças de estado. Uma curva de aquecimento resume as mudanças: para cada mudança de estado, a energia deve ser adicionada. Conhecido como o calor latente. Os valores de energia real para essas mudanças físicas de estado para uma variedade de substâncias são tratados com mais detalhes nas Notas Energéticas. CUIDADO LATENTE ESPECÍFICO O calor latente para o estado muda o líquido ltgt sólido é chamado de calor latente específico de fusão (para derretimento ou congelamento). O calor latente para o estado muda o gás ltgt líquido é chamado de calor latente específico de vaporização (para condensação, evaporação ou fervura) Para mais informações sobre o calor latente, veja minhas notas de física sobre o calor latente específico Explicado usando a teoria das partículas cinéticas de gases e sólidos. É quando um sólido, em aquecimento, muda diretamente para um gás sem derreter, E o gás no resfriamento reforma um sólido diretamente sem condensação em um líquido. Sublimação geralmente envolve apenas uma mudança física, mas nem sempre é tão simples (ver cloreto de amônio). Teoria em termos de partículas. Quando o sólido é aquecido, as partículas vibram com força crescente da energia térmica adicionada. Se as partículas tiverem energia cinética suficiente de vibração para superar parcialmente as forças atraentes de partículas, você esperaria que o sólido funde. No entanto, se as partículas neste ponto tiverem energia suficiente neste ponto que levariam a ferver, o líquido NÃO formará e o sólido se transformará diretamente em um gás. Mudança endotérmica geral. Energia absorvida e introduzida no sistema. Ao esfriar, as partículas se movem mais devagar e têm menos energia cinética. Eventualmente, quando a energia cinética das partículas é suficientemente baixa, permitirá que as forças atrativas de partícula produzam um líquido. MAS a energia pode ser suficientemente baixa para permitir a formação direta do sólido, isto é, as partículas NÃO têm energia cinética suficiente para manter um estado líquido. Mudança exotérmica geral. Energia liberada e distribuída para os arredores. Mesmo a temperatura ambiente, garrafas de iodo sólido mostram cristais formando no topo da garrafa acima do sólido. Quanto mais quente for o laboratório, mais cristais se formam quando resfriam à noite. Se você aquecer suavemente o iodo num tubo de ensaio, você vê o iodo prontamente sublime e recristaliza na superfície do resfriador perto da parte superior do tubo de ensaio. A formação de uma forma particular de geada envolve o congelamento direto de vapor de água (gás). Frost também pode evaporar diretamente de volta ao vapor de água (gás) e isso acontece nos invernos secos e extremamente frios do Deserto de Gobi em um dia ensolarado. H 2 O (s) H 2 O (g) (apenas alterações físicas) O dióxido de carbono sólido (gelo seco) é formado ao arrefecer o gás para menos de 78 o C. Ao aquecer, ele muda diretamente para um gás muito frio. Condensando qualquer vapor de água no ar para uma névoa, daí o seu uso em efeitos de estágio. CO 2 (s) CO 2 (g) (apenas alterações físicas) Ao aquecer fortemente em um tubo de ensaio, cloreto de amónio sólido branco. Se decompõe em uma mistura de dois gases incolores, amônia e cloreto de hidrogênio. Ao arrefecer, a reação é revertida e as reformas de cloreto de amônio sólido na superfície superior mais fria do tubo de ensaio. Cloreto de amónio calor energia cloreto de hidrogénio amoníaco T envolve mudanças químicas e físicas e é tão complicado do que os exemplos 1. a 3. De fato, os cristais de cloreto de amônio iônico se transformam em amoníaco covalente e gases do cloreto de hidrogênio que são naturalmente muito mais voláteis ( As substâncias covalentes geralmente têm pontos de fusão e ponto de ebulição muito mais baixos do que substâncias iónicas). A imagem de partículas líquidas não figura aqui, mas os outros modelos se aplicam completamente além das mudanças de estado envolvendo a formação de líquido. Modelo de partículas de GAS e links de modelos de partículas SOLID. ATENÇÃO, em um nível mais alto de estudo. Você precisa estudar o diagrama de fases do gls para a água e a curva de pressão de vapor do gelo a temperaturas específicas. Por exemplo, se a pressão de vapor ambiente for menor que a pressão de vapor de equilíbrio à temperatura do gelo, a sublimação pode ocorrer prontamente. A neve e o gelo nas regiões mais frias do deserto de Gobi não se derretem no Sol, eles lentamente desaparecem suavemente 2 h. Mais sobre as mudanças de calor em mudanças físicas do estado As mudanças de estado físico, ou seja, o líquido de ltgt do gás ltgt sólido também são acompanhados por mudanças de energia. Para derreter um sólido, ou um vaporizador, um líquido, a energia de calor deve ser absorvida ou absorvida pelos arredores, de modo que são mudanças de energia endotérmicas. O sistema é aquecido para efetuar essas mudanças. Para condensar um gás ou congelar um sólido, a energia de calor deve ser removida ou distribuída para os ambientes, então estas são mudanças de energia exotérmica. O sistema é resfriado para efetuar essas mudanças. De um modo geral, quanto maior as forças entre as partículas, maior a energia necessária para efetuar a mudança de estado E quanto maior o ponto de fusão e ponto de ebulição. Uma comparação da energia necessária para derreter ou ferver diferentes tipos de substância (Isto é mais para estudantes de nível avançado). A mudança de energia térmica envolvida em uma mudança de estado pode ser expressa em kJmol de substância para uma comparação justa. Na tabela abaixo, a massa fundida 916H é a energia necessária para derreter 1 mole da substância (massa da fórmula em g). 916H vap é a energia necessária para vaporizar por evaporação ou ferver 1 mole da substância (massa da fórmula em g). Para pequenas moléculas covalentes simples, a energia absorvida pelo material é relativamente pequena para derreter ou vaporizar a substância e quanto maior a molécula, maiores são as forças intermoleculares. Essas forças são fracas em comparação com as ligações químicas que mantêm átomos juntos em uma molécula em si. São necessárias energias relativamente baixas para derreter ou vaporizá-las. Essas substâncias têm pontos de fusão relativamente baixos e pontos de ebulição. Para redes 3D fortemente ligadas, e. (Iii) e uma rede metálica de íons e elétrons externos livres (ligação metamática), as estruturas são muito mais fortes de forma contínua devido à ligação química contínua em toda a estrutura. Conseqüentemente, são necessárias energias muito maiores para derreter ou vaporizar o material. É por isso que eles têm muito mais pontos de fusão e pontos de ebulição. Tipo de ligação, estrutura e forças de atração operacionais Ponto de fusão K (Kelvin) o C 273 Energia necessária para derreter a substância Ponto de ebulição K (Kelvin) o C 273 Energia necessária para ferver a substância 3a. O QUE ACONTECE DE PARTÍCULAS QUANDO UM SOLIDO DISSOLVE EM UM SOLVENTE LÍQUIDO O que as palavras SOLUENTE, SOLUÇÃO e SOLUÇÃO significam Quando um sólido (o soluto) se dissolve em um líquido (o solvente), a mistura resultante é chamada de solução. Em geral: soluto dissolvido solução gt Assim, o soluto é o que dissolve em um solvente, um solvente é um líquido que dissolve coisas e a solução é o resultado de dissolver algo em um solvente. O sólido perde toda a sua estrutura regular e as partículas sólidas individuais (moléculas ou íons) estão agora completamente livres uma da outra e mistura aleatoriamente com as partículas líquidas originais, e todas as partículas podem se mover ao acaso. Isso descreve o sal que se dissolve em água, o açúcar que se dissolve em chá ou cera que se dissolve em um solvente hidrocarboneto como o espírito branco. Geralmente não envolve uma reação química, por isso geralmente é um exemplo de uma mudança física. Quaisquer que sejam as mudanças no volume do líquido sólido, em comparação com a solução final, a Lei da Conservação da Massa ainda se aplica. Isto significa: Massa de massa solúvel sólida de massa solvente líquida de solução após mistura e dissolução. Você não pode criar massa ou perder massa. Mas mude a massa de substâncias para outra forma. Se o solvente for evaporado. Então o sólido é reformado, e. Se uma solução de sal for deixada de fora por um longo período de tempo ou suavemente aquecida para acelerar as coisas, eventualmente formam-se cristais de sal, o processo é chamado de cristalização. 3b. O QUE ACONTECE COM PARTÍCULAS QUANDO DOIS LÍQUIDOS COMPLETAMENTE MISTEM COM O QUE FAZ A PALAVRA MISCÍVEL MEIO Usando o modelo de partículas para explicar líquidos miscíveis. Se dois líquidos se misturam completamente em termos de suas partículas, eles são chamados de líquidos miscíveis porque se dissolvem completamente uns nos outros. Isso é mostrado no diagrama abaixo onde as partículas se misturam completamente e se movem ao acaso. O processo pode ser revertido por destilação fracionada. 3c. O QUE ACONTECE DE PARTÍCULAS QUANDO DOIS LÍQUIDOS NÃO MISTEM COM O QUE É QUE A PALAVRA IMEDIATA SIGNIFICA POR QUE OS LÍQUIDOS NÃO MISTEM Utilizando o modelo de partículas para explicar líquidos imiscíveis. Se os dois líquidos não se misturam. Eles formam duas camadas separadas e são conhecidos como líquidos imiscíveis, ilustrados no diagrama abaixo, onde o líquido roxo inferior será mais denso do que a camada superior do líquido verde. Você pode separar esses dois líquidos usando um funil de separação. A razão para isso é que a interação entre as moléculas de um dos líquidos sozinho é mais forte do que a interação entre as duas moléculas diferentes dos diferentes líquidos. Por exemplo, a força de atração entre as moléculas de água é muito maior do que moléculas de óleo ou moléculas de água de óleo, então duas camadas separadas formam-se porque as moléculas de água, em termos de mudança de energia, são favorecidas ao se juntarem. 3d. Como é utilizado um funil de separação 1. A mistura é colocada no funil de separação com a rolha encostada e a torneira fechada e as camadas deixadas para assentar. 2. A rolha é removida e a torneira é aberta para que você possa executar com cuidado a camada cinza inferior em primeiro lugar em uma taça. 3. A torneira é então fechada novamente, deixando para trás o líquido da camada amarela superior, separando assim os dois líquidos imiscíveis. Apêndice 1 algumas imagens de partículas SIMPLES de ELEMENTOS, COMPOSTOS e MISTURAS GCEEIGCSE escolha múltipla QUIZ em estados de gases da matéria, líquidos sólidos de amplificador Alguns exercícios básicos fáceis de KS3 ciência QCA 7G quotParticle modelo de sólidos, líquidos e gases Questões de escolha múltipla para revisão de ciência em gases , Modelos de partículas de líquidos e sólidos, propriedades, explicando as diferenças entre eles. Veja também para cálculos de gás gcse revisão de química revisões detalhadas gratuitas sobre estados de assunto para ajudar a revisar igcse quimica igcse quimica notas de revisão em estados de matéria revisão de química de nível O notas detalhadas gratuitas sobre estados de assunto para ajudar a revisar a química livre de gcse notas detalhadas gratuitas em estados de Assunto para ajudar a revisar o site on-line gratuito de Química do O para ajudar a revisar os estados da matéria para o site online gratuito de quimica de gcse para ajudar a revisar os estados da matéria para o site on-line gratuito da química da igcse para ajudar a revisar os estados do nível de química da matéria como ter sucesso em questões sobre estados De matéria para química gcse como ter sucesso na química de igcse como ter sucesso na química de nível O um bom site para perguntas gratuitas sobre estados de assunto para ajudar a passar questões de química de gcse em estados de matéria um bom site para ajuda gratuita para passar a química de igcse com Notas de revisão sobre estados de assunto um bom site para ajuda gratuita para passar Química de nível O, quais são os três estados de elaboração de matéria Um diagrama do diagrama do modelo de partículas de um gás, a teoria das partículas de um gás, desenhar um diagrama modelo de partículas de um líquido, a teoria das partículas de um líquido, desenhar um diagrama modelo de partículas de um sólido, a teoria das partículas de um sólido, o que é a difusão why can you have diffusion in gases and liquids but not in solids what are the limitations of the particle model of a gas liquid or solid how to use the particle model to explain the properties of a gas, what causes gas pressure how to use the particle model to explain the properties of a solid, how to use the particle model to explain the properties of a solid, why is a gas easily compressed but difficult to compress a liquid or solid how do we use the particle model to explain changes of state explaining melting with the particle model, explaining boiling with the particle model, explaining evaporation using the particle model, explaining condensing using the particle model, explaining freezing with the particle model, how do you read a thermometer wor king out the state of a substance at a particular temperature given its melting point and boiling point, how to draw a cooling curve, how to draw a heating curve, how to explain heatingcooling curves in terms of state changes and latent heat, what is sublimation what substances sublime explaining endothermic and exothermic energy changes of state, using the particle model to explain miscible and immiscible liquids GASES, LIQUIDS, SOLIDS, States of Matter, particle models, theory of state changes, melting, boiling, evaporation, condensing, freezing, solidifying, cooling curves, 1.1 Three states of matter: 1.1a gases, 1.1b liquids, 1.1c solids 2. State changes: 2a evaporation and boiling, 2b condensation, 2c distillation, 2d melting, 2e freezing, 2f cooling and heating curves and relative energy changes, 2g sublimation 3. Dissolving, solutions. miscibleimmiscible liquids Boiling Boiling point Brownian motion Changes of state Condensing Cooling curve Diffusion Dissolving Evaporation Freezing Freezing point Gas particle picture Heating curve Liquid particle picture Melting Melting point miscibleimmiscible liquids Properties of gases Properties of liquids Properties of solids solutions sublimation Solid particle picture GCSEIGCSE multiple choice QUIZ on states of matter gases liquids solids practice revision questions Revision notes on particle models and properties of gases, liquids and solids KS4 Science GCSEIGCSEO level Chemistry Information on particle models and properties of gases, liquids and solids for revising for AQA GCSE Science, Edexcel Science chemistry IGCSE Chemistry notes on particle models and properties of gases, liquids and solids OCR 21st Century Science, OCR Gateway Science notes on particle models and properties of gases, liquids and solids WJEC gcse science chemistry notes on particl e models and properties of gases, liquids and solids CIE O Level chemistry CIE IGCSE chemistry notes on particle models and properties of gases, liquids and solids CCEACEA gcse science chemistry (revise courses equal to US grade 8, grade 9 grade 10) science chemistry courses revision guides explanation chemical equations for particle models and properties of gases, liquids and solids educational videos on particle models and properties of gases, liquids and solids guidebooks for revising particle models and properties of gases, liquids and solids textbooks on particle models and properties of gases, liquids and solids state changes amp particle model for AQA AS chemistry, state changes amp particle model for Edexcel A level AS chemistry, state changes amp particle model for A level OCR AS chemistry A, state changes amp particle model for OCR Salters AS chemistry B, state changes amp particle model for AQA A level chemistry, state changes amp particle model for A level Edexcel A level c hemistry, state changes amp particle model for OCR A level chemistry A, state changes amp particle model for A level OCR Salters A level chemistry B state changes amp particle model for US Honours grade 11 grade 12 state changes amp particle model for pre-university chemistry courses pre-university A level revision notes for state changes amp particle model A level guide notes on state changes amp particle model for schools colleges academies science course tutors images pictures diagrams for state changes amp particle model A level chemistry revision notes on state changes amp particle model for revising module topics notes to help on understanding of state changes amp particle model university courses in science careers in science jobs in the industry laboratory assistant apprenticeships technical internships USA US grade 11 grade 11 AQA A level chemistry notes on state changes amp particle model Edexcel A level chemistry notes on state changes amp particle model for OCR A level chem istry notes WJEC A level chemistry notes on state changes amp particle model CCEACEA A level chemistry notes on state changes amp particle model for university entrance examinationsMost people are familiar with the phrase, quotthis will kill two birds with one stonequot. If you39re not, the phase refers to an approach that addresses two objectives in one action. (Unfortunately, the expression itself is rather unpleasant, as most of us don39t want to throw stones at innocent animals) Today I39m going to cover some basics on two great features in SQL Server: the Columnstore index (available only in SQL Server Enterprise) and the SQL Query Store . Microsoft actually implemented the Columnstore index in SQL 2012 Enterprise, though they39ve enhanced it in the last two releases of SQL Server. Microsoft introduced the Query Store in SQL Server 2016. So, what are these features and why are they important Well, I have a demo that will introduce both features and show how they can help us. Before I go any further, I also cover this (and other SQL 2016 features) in my CODE Magazine article on new features SQL 2016. As a basic introduction, the Columnstore index can help speed up queries that scanaggregate over large amounts of data, and the Query Store tracks query executions, execution plans, and runtime statistics that you39d normally need to collect manually. Trust me when I say, these are great features. For this demo, I39ll be using the Microsoft Contoso Retail Data Warehouse demo database. Loosely speaking, Contoso DW is like quota really big AdventureWorksquot, with tables containing millions of rows. (The largest AdventureWorks table contains roughly 100,000 rows at most). You can download the Contoso DW database here: microsoften-usdownloaddetails. aspxid18279. Contoso DW works very well when you want to test performance on queries against larger tables. Contoso DW contains a standard data warehouse Fact table called FactOnLineSales, with 12.6 million rows. That39s certainly not the largest data warehouse table in the world, but it39s not child39s play either. Suppose I want to summarize product sales amount for 2009, and rank the products. I might query the fact table and join to the Product Dimension table and use a RANK function, like so: Here39s a partial result set of the top 10 rows, by Total Sales. On my laptop (i7, 16 GB of RAM), the query takes anywhere from 3-4 seconds to run. That might not seem like the end of the world, but some users might expect near-instant results (the way you might see near-instant results when using Excel against an OLAP cube). The only index I currently have on this table is a clustered index on a sales key. If I look at the execution plan, SQL Server makes a suggestion to add a covering index to the table: Now, just because SQL Server suggests an index, doesn39t mean you should blindly create indexes on every quotmissing indexquot message. However, in this instance, SQL Server detects that we are filtering based on year, and using the Product Key and Sales Amount. So, SQL Server suggests a covering index, with the DateKey as the index key field. The reason we call this a quotcoveringquot index is because SQL Server will quotbring along the non-key fieldsquot we used in the query, quotfor the ridequot. That way, SQL Server doesn39t need to use the table or the clustered index at all the database engine can simply use the covering index for the query. Covering indexes are popular in certain data warehousing and reporting database scenarios, though they do come at a cost of the database engine maintaining them. Note: Covering indexes have been around for a long time, so I haven39t yet covered the Columnstore index and the Query Store. So, I will add the covering index: If I re-execute the same query I ran a moment ago (the one that aggregated the sales amount for each product), the query sometimes seems to run about a second faster, and I get a different execution plan, one that uses an Index Seek instead of an Index Scan (using the date key on the covering index to retrieve sales for 2009). So, prior to the Columnstore Index, this could be one way to optimize this query in much older versions of SQL Server. It runs a little faster than the first one, and I get an execution plan with an Index Seek instead of an Index Scan. However, there are some issues: The two execution operators quotIndex Seekquot and quotHash Match (Aggregate)quot both essentially operate quotrow by rowquot. Imagine this in a table with hundreds of millions of rows. Related, think about the contents of a fact table: in this case, a single date key value andor a single product key value might be repeated across hundreds of thousands of rows (remember, the fact table also has keys for geography, promotion, salesman, etc.) So, when the quotIndex Seekquot and quotHash Matchquot work row by row, they are doing so over values that might be repeated across many other rows. This is normally where I39d segue to the SQL Server Columnstore index, which offers a scenario to improve the performance of this query in amazing ways. But before I do that, let39s go back in time. Let39s go back to the year 2010, when Microsoft introduced an add-in for Excel known as PowerPivot. Many people probably remember seeing demos of PowerPivot for Excel, where a user could read millions of rows from an outside data source into Excel. PowerPivot would compress the data, and provide an engine to create Pivot Tables and Pivot Charts that performed at amazing speeds against the compressed data. PowerPivot used an in-memory technology that Microsoft termed quotVertiPaqquot. This in-memory technology in PowerPivot would basically take duplicate business keyforeign key values and compress them down to a single vector. The in-memory technology would also scanaggregate these values in parallel, in blocks of several hundred at a time. The bottom line is that Microsoft baked a large amount of performance enhancements into the VertiPaq in-memory feature for us to use, right out of the proverbial box. Why am I taking this little stroll down memory lane Because in SQL Server 2012, Microsoft implemented one of the most important features in the history of their database engine: the Columnstore index. The index is really an index in name only: it is a way to take a SQL Server table and create a compressed, in-memory columnstore that compresses duplicate foreign key values down to single vector values. Microsoft also created a new buffer pool to read these compressed vector values in parallel, creating the potential for huge performance gains. So, I39m going to create a columnstore index on the table, and I39ll see how much better (and more efficiently) the query runs, versus the query that runs against the covering index. So, I39ll create a duplicate copy of FactOnlineSales (I39ll call it FactOnlineSalesDetailNCCS), and I39ll create a columnstore index on the duplicated table that way I won39t interfere with the original table and the covering index in any way. Next, I39ll create a columnstore index on the new table: Note several things: I39ve specified several foreign key columns, as well as the Sales Amount. Remember that a columnstore index is not like a traditional row-store index. There is no quotkeyquot. We are simply indicating which columns SQL Server should compress and place in an in-memory columnstore. To use the analogy of PowerPivot for Excel when we create a columnstore index, we39re telling SQL Server to essentially do the same thing that PowerPivot did when we imported 20 million rows into Excel using PowerPivot So, I39ll re-run the query, this time using the duplicated FactOnlineSalesDetailNCCS table that contains the columnstore index. This query runs instantly in less than a second. And I can also say that even if the table had hundreds of millions of rows, it would still run at the proverbial quotbat of an eyelashquot. We could look at the execution plan (and in a few moments, we will), but now it39s time to cover the Query Store feature. Imagine for a moment, that we ran both queries overnight: the query that used the regular FactOnlineSales table (with the covering index) and then the query that used the duplicated table with the Columnstore index. When we log in the following morning, we39d like to see the execution plan for both queries as they took place, as well as the execution statistics. In other words, we39d like to see the same statistics that we39d be able to see if we ran both queries interactively in SQL Management Studio, turned in TIME and IO Statistics, and viewed the execution plan right after executing the query. Well, that39s what the Query Store allows us to do we can turn on (enable) Query Store for a database, which will trigger SQL Server to store query execution and plan statistics so that we can view them later. So, I39m going to enable the Query Store on the Contoso database with the following command (and I39ll also clear out any caching): Then I39ll run the two queries (and quotpretendquot that I ran them hours ago): Now let39s pretend they ran hours ago. According to what I said, the Query Store will capture the execution statistics. So how do I view them Fortunately, that39s quite easy. If I expand the Contoso DW database, I39ll see a Query Store folder. The Query Store has tremendous functionality and I39ll try to cover much of it in subsequent blog posts. But for right now, I want to view execution statistics on the two queries, and specifically examine the execution operators for the columnstore index. So I39ll right-click on the Top Resource Consuming Queries and run that option. That gives me a chart like the one below, where I can see execution duration time (in milliseconds) for all queries that have been executed. In this instance, Query 1 was the query against the original table with the covering index, and Query 2 was against the table with the columnstore index. The numbers don39t lie the columnstore index outperformed the original tablecovering index by a factor of almost 7 to 1. I can change the metric to look at memory consumption instead. In this case, note that query 2 (the columnstore index query) used far more memory. This demonstrates clearly why the columnstore index represents quotin-memoryquot technology SQL Server loads the entire columnstore index in memory, and uses a completely different buffer pool with enhanced execution operators to process the index. OK, so we have some graphs to view execution statistics can we see the execution plan (and execution operators) associated with each execution Yes, we can If you click on the vertical bar for the query that used the columnstore index, you39ll see the execution plan below. The first thing we see is that SQL Server performed a columnstore index scan, and that represented nearly 100 of the cost of the query. You might be saying, quotWait a minute, the first query used a covering index and performed an index seek so how can a columnstore index scan be fasterquot That39s a legitimate question, and fortunately there39s an answer. Even when the first query performed an index seek, it still executed quotrow by rowquot. If I put the mouse over the columnstore index scan operator, I see a tooltip (like the one below), with one important setting: the Execution Mode is BATCH (as opposed to ROW . which is what we had with the first query using the covering index). That BATCH mode tells us that SQL Server is processing the compressed vectors (for any foreign key values that are duplicated, such as the product key and date key) in batches of almost 1,000, in parallel. So SQL Server is still able to process the columnstore index much more efficiently. Additionally, if I place the mouse over the Hash Match (Aggregate) task, I also see that SQL Server is aggregating the columnstore index using Batch mode (although the operator itself represents such a tiny percent of the cost of the query) Finally, you might be asking, quotOK, so SQL Server compresses the values in the data, treats the values as vectors, and read them in blocks of almost a thousand values in parallel but my query only wanted data for 2009. So is SQL Server scanning over the entire set of dataquot Again, a good question. The answer is, quotNot reallyquot. Fortunately for us, the new columnstore index buffer pool performs another function called quotsegment eliminationquot. Basically, SQL Server will examine the vector values for the date key column in the columnstore index, and eliminate segments that are outside the scope of the year 2009. I39ll stop here. In subsequent blog posts I39ll cover both the columnstore index and Query Store in more detail. Essentially, what we39ve seen here today is that the Columnstore index can significantly speed up queries that scanaggregate over large amounts of data, and the Query Store will capture query executions and allow us to examine execution and performance statistics later. In the end, we39d like to produce a result set that shows the following. Notice three things: The columns essentially pivot all of the possible Return Reasons, after showing the sales amount The result set contains subtotals by the week ending (Sunday) date across all clients (where the Client is NULL) The result set contains a grand total row (where the Client and Date are both NULL) First, before I get into the SQL end we could use the dynamic pivotmatrix capability in SSRS. We would simply need to combine the two result sets by one column and then we could feed the results to the SSRS matrix control, which will spread the return reasons across the columns axis of the report. However, not everyone uses SSRS (though most people should). But even then, sometimes developers need to consume result sets in something other than a reporting tool. So for this example, let39s assume we want to generate the result set for a web grid page and possibly the developer wants to quotstrip outquot the subtotal rows (where I have a ResultSetNum value of 2 and 3) and place them in a summary grid. So bottom line, we need to generate the output above directly from a stored procedure. And as an added twist next week there could be Return Reason X and Y and Z. So we don39t know how many return reasons there could be. We simple want the query to pivot on the possible distinct values for Return Reason. Here is where the T-SQL PIVOT has a restriction we need to provide it the possible values. Since we won39t know that until run-time, we need to generate the query string dynamically using the dynamic SQL pattern. The dynamic SQL pattern involves generating the syntax, piece by piece, storing it in a string, and then executing the string at the end. Dynamic SQL can be tricky, as we have to embed syntax inside a string. But in this case, it our only true option if we want to handle a variable number of return reasons. I39ve always found that the best way to create a dynamic SQL solution is by figuring out what the quotidealquot generated-query would be at the end (in this case, given the Return reasons we know about).and then reverse-engineering it by piecing it together one part at a time. And so, here is the SQL we need if we knew those Return Reasons (A through D) were static and would not change. The query does the following: Combines the data from SalesData with the data from ReturnData, where we quothard-wirequot the word Sales as an Action Type form the Sales Table, and then use the Return Reason from the Return Data into the same ActionType column. That will give us a clean ActionType column on which to pivot. We are combining the two SELECT statements into a common table expression (CTE), which is basically a derived table subquery that we subsequently use in the next statement (to PIVOT) A PIVOT statement against the CTE, that sums the dollars for the Action Type being in one of the possible Action Type values. Note that this isn39t the final result set. We are placing this into a CTE that reads from the first CTE. The reason for this is because we want to do multiple groupings at the end. The final SELECT statement, that reads from the PIVOTCTE, and combines it with a subsequent query against the same PIVOTCTE, but where we also implement two groupings in the GROUPING SETS feature in SQL 2008: GROUPING by the Week End Date (dbo. WeekEndingDate) GROUPING for all rows () So if we knew with certainty that we39d never have more return reason codes, then that would be the solution. However, we need to account for other reason codes. So we need to generate that entire query above as one big string where we construct the possible return reasons as one comma separated list. I39m going to show the entire T-SQL code to generate (and execute) the desired query. And then I39ll break it out into parts and explain each step. So first, here39s the entire code to dynamically generate what I39ve got above. There are basically five steps we need to cover. Passo 1 . we know that somewhere in the mix, we need to generate a string for this in the query: SalesAmount, Reason A, Reason B, Reason C, Reason D0160016001600160 What we can do is built a temporary common table expression that combines the hard wired quotSales Amountquot column with the unique list of possible reason codes. Once we have that in a CTE, we can use the nice little trick of FOR XML PATH(3939) to collapse those rows into a single string, put a comma in front of each row that the query reads, and then use STUFF to replace the first instance of a comma with an empty space. This is a trick that you can find in hundreds of SQL blogs. So this first part builds a string called ActionString that we can use further down. Passo 2 . we also know that we39ll want to SUM the generatedpivoted reason columns, along with the standard sales column. So we39ll need a separate string for that, which I39ll call SUMSTRING. I39ll simply use the original ActionString, and then REPLACE the outer brackets with SUM syntax, plus the original brackets. Step 3: Now the real work begins. Using that original query as a model, we want to generate the original query (starting with the UNION of the two tables), but replacing any references to pivoted columns with the strings we dynamically generated above. Also, while not absolutely required, I39ve also created a variable to simply any carriage returnline feed combinations that we want to embed into the generated query (for readability). So we39ll construct the entire query into a variable called SQLPivotQuery. Passo 4. We continue constructing the query again, concatenating the syntax we can quothard-wirequot with the ActionSelectString (that we generated dynamically to hold all the possible return reason values) Step 5 . Finally, we39ll generate the final part of the Pivot Query, that reads from the 2 nd common table expression (PIVOTCTE, from the model above) and generates the final SELECT to read from the PIVOTCTE and combine it with a 2 nd read against PIVOTCTE to implement the grouping sets. Finally, we can quotexecutequot the string using the SQL system stored proc spexecuteSQL So hopefully you can see that the process to following for this type of effort is Determine what the final query would be, based on your current set of data and values (i. e. built a query model) Write the necessary T-SQL code to generate that query model as a string. Arguably the most important part is determining the unique set of values on which you39ll PIVOT, and then collapsing them into one string using the STUFF function and the FOR XML PATH(3939) trick So whats on my mind today Well, at least 13 items Two summers ago, I wrote a draft BDR that focused (in part) on the role of education and the value of a good liberal arts background not just for the software industry but even for other industries as well. One of the themes of this particular BDR emphasized a pivotal and enlightened viewpoint from renowned software architect Allen Holub regarding liberal arts. Ill (faithfully) paraphrase his message: he highlighted the parallels between programming and studying history, by reminding everyone that history is reading and writing (and Ill add, identifying patterns), and software development is also reading and writing (and again, identifying patterns). And so I wrote an opinion piece that focused on this and other related topics. But until today, I never got around to either publishingposting it. Every so often Id think of revising it, and Id even sit down for a few minutes and make some adjustments to it. But then life in general would get in the way and Id never finish it. So what changed A few weeks ago, fellow CoDe Magazine columnist and industry leader Ted Neward wrote a piece in his regular column, Managed Coder , that caught my attention. The title of the article is On Liberal Arts. and I highly recommend that everyone read it. Ted discusses the value of a liberal arts background, the false dichotomy between a liberal arts background and success in software development, and the need to writecommunicate well. He talks about some of his own past encounters with HR personnel management regarding his educational background. He also emphasizes the need to accept and adapt to changes in our industry, as well as the hallmarks of a successful software professional (being reliable, planning ahead, and learning to get past initial conflict with other team members). So its a great read, as are Teds other CoDe articles and blog entries. It also got me back to thinking about my views on this (and other topics) as well, and finally motivated me to finish my own editorial. So, better late than never, here are my current Bakers Dozen of Reflections: I have a saying: Water freezes at 32 degrees . If youre in a trainingmentoring role, you might think youre doing everything in the world to help someone when in fact, theyre only feeling a temperature of 34 degrees and therefore things arent solidifying for them. Sometimes it takes just a little bit more effort or another ideachemical catalyst or a new perspective which means those with prior education can draw on different sources. Water freezes at 32 degrees . Some people can maintain high levels of concentration even with a room full of noisy people. Im not one of them occasionally I need some privacy to think through a critical issue. Some people describe this as you gotta learn to walk away from it. Stated another way, its a search for the rarefied air. This past week I spent hours in half-lit, quiet room with a whiteboard, until I fully understood a problem. It was only then that I could go talk with other developers about a solution. The message here isnt to preach how you should go about your business of solving problems but rather for everyone to know their strengths and what works, and use them to your advantage as much as possible. Some phrases are like fingernails on a chalkboard for me. Use it as a teaching moment is one. (Why is it like fingernails on a chalkboard Because if youre in a mentoring role, you should usually be in teaching moment mode anyway, however subtly). Heres another I cant really explain it in words, but I understand it. This might sound a bit cold, but if a person truly cant explain something in words, maybe they dont understand. Sure, a person can have a fuzzy sense of how something works I can bluff my way through describing how a digital camera works but the truth is that I dont really understand it all that well. There is a field of study known as epistemology (the study of knowledge). One of the fundamental bases of understanding whether its a camera or a design pattern - is the ability to establish context, to identify the chain of related events, the attributes of any components along the way, etc. Yes, understanding is sometimes very hard work, but diving into a topic and breaking it apart is worth the effort. Even those who eschew certification will acknowledge that the process of studying for certification tests will help to fill gaps in knowledge. A database manager is more likely to hire a database developer who can speak extemporaneously (and effortlessly) about transaction isolation levels and triggers, as opposed to someone who sort of knows about it but struggles to describe their usage. Theres another corollary here. Ted Neward recommends that developers take up public speaking, blogging, etc. I agree 100. The process of public speaking and blogging will practically force you to start thinking about topics and breaking down definitions that you might have otherwise taken for granted. A few years ago I thought I understood the T-SQL MERGE statement pretty well. But only after writing about it, speaking about, fielding questions from others who had perspectives that never occurred to me that my level of understanding increased exponentially. I know a story of a hiring manager who once interviewed an authordeveloper for a contract position. The hiring manager was contemptuous of publications in general, and barked at the applicant, So, if youre going to work here, would you rather be writing books or writing code Yes, Ill grant that in any industry there will be a few pure academics. But what the hiring manager missed was the opportunities for strengthening and sharpening skill sets. While cleaning out an old box of books, I came across a treasure from the 1980s: Programmers at Work. which contains interviews with a very young Bill Gates, Ray Ozzie, and other well-known names. Every interview and every insight is worth the price of the book. In my view, the most interesting interview was with Butler Lampson. who gave some powerful advice. To hell with computer literacy. Its absolutely ridiculous. Study mathematics. Learn to think. Read. Write. These things are of more enduring value. Learn how to prove theorems: A lot of evidence has accumulated over the centuries that suggests this skill is transferable to many other things. Butler speaks the truth . Ill add to that point learn how to play devils advocate against yourself. The more you can reality-check your own processes and work, the better off youll be. The great computer scientistauthor Allen Holub made the connection between software development and the liberal arts specifically, the subject of history. Here was his point: what is history Reading and writing. What is software development Among other things, reading and writing . I used to give my students T-SQL essay questions as practice tests. One student joked that I acted more like a law professor. Well, just like Coach Donny Haskins said in the movie Glory Road, my way is hard. I firmly believe in a strong intellectual foundation for any profession. Just like applications can benefit from frameworks, individuals and their thought processes can benefit from human frameworks as well. Thats the fundamental basis of scholarship. There is a story that back in the 1970s, IBM expanded their recruiting efforts in the major universities by focusing on the best and brightest of liberal arts graduates. Even then they recognized that the best readers and writers might someday become strong programmersystems analysts. (Feel free to use that story to any HR-type who insists that a candidate must have a computer science degree) And speaking of history: if for no other reason, its important to remember the history of product releases if Im doing work at a client site thats still using SQL Server 2008 or even (gasp) SQL Server 2005, I have to remember what features were implemented in the versions over time. Ever have a favorite doctor whom you liked because heshe explained things in plain English, gave you the straight truth, and earned your trust to operate on you Those are mad skills . and are the result of experience and HARD WORK that take years and even decades to cultivate. There are no guarantees of job success focus on the facts, take a few calculated risks when youre sure you can see your way to the finish line, let the chips fall where they may, and never lose sight of being just like that doctor who earned your trust. Even though some days I fall short, I try to treat my client and their data as a doctor would treat patients. Even though a doctor makes more money There are many clichs I detest but heres one I dont hate: There is no such thing as a bad question. As a former instructor, one thing that drew my ire was hearing someone criticize another person for asking a supposedly, stupid question. A question indicates a person acknowledges they have some gap in knowledge theyre looking to fill. Yes, some questions are better worded than others, and some questions require additional framing before they can be answered. But the journey from forming a question to an answer is likely to generate an active mental process in others. There are all GOOD things. Many good and fruitful discussions originate with a stupid question. I work across the board in SSIS, SSAS, SSRS, MDX, PPS, SharePoint, Power BI, DAX all the tools in the Microsoft BI stack. I still write some. NET code from time to time. But guess what I still spend so much time doing writing T-SQL code to profile data as part of the discovery process. All application developers should have good T-SQL chops. Ted Neward writes (correctly) about the need to adapt to technology changes. Ill add to that the need to adapt to clientemployer changes. Companies change business rules. Companies acquire other companies (or become the target of an acquisition). Companies make mistakes in communicating business requirements and specifications. Yes, we can sometimes play a role in helping to manage those changes and sometimes were the fly, not the windshield. These sometimes cause great pain for everyone, especially the I. T. people. This is why the term fact of life exists we have to deal with it. Just like no developer writes bug-free code every time, no I. T. person deals well with change every single time. One of the biggest struggles Ive had in my 28 years in this industry is showing patience and restraint when changes are flying from many different directions. Here is where my prior suggestion about searching for the rarified air can help. If you can manage to assimilate changes into your thought process, and without feeling overwhelmed, odds are youll be a significant asset. In the last 15 months Ive had to deal with a huge amount of professional change. Its been very difficult at times, but Ive resolved that change will be the norm and Ive tried to tweak my own habits as best I can to cope with frequent (and uncertain) change. Its hard, very hard. But as coach Jimmy Duggan said in the movie A League of Their Own: Of course its hard. If it wasnt hard, everyone would do it. The hard, is what makes it great . A powerful message. Theres been talk in the industry over the last few years about conduct at professional conferences (and conduct in the industry as a whole). Many respected writers have written very good editorials on the topic. Heres my input, for what its worth. 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. Então, você tem isso. 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.

No comments:

Post a Comment