Why query cache plan kept dynamic queries but not sp?how to minimize the effect of updating statistics on the plan cache?Is execution plan cached “better” for stored procedures than for a non-dynamic query?Can a plan “age” reach zero?How to regenerate execution plans after clearing the plan cache?Tracking Down Plan Cache ClearingMissing execution plans for stored proceduresSQL Server cached an execution plan which is not optimal in some cases and uses it for all consequent queriesInstant plan cache cleanupPlan cache mysterySQL Buffer Pool and Plan cache

Was this a power play by Daenerys?

Is a vertical stabiliser needed for straight line flight in a glider?

How are Core iX names like Core i5, i7 related to Haswell, Ivy Bridge?

Is there a faster way to calculate Abs[z]^2 numerically?

Does Lawful Interception of 4G / the proposed 5G provide a back door for hackers as well?

Exception propagation: When to catch exceptions?

The lexical root of the perfect tense forms differs from the lexical root of the infinitive form

Why does TypeScript pack a Class in an IIFE?

How can a Lich look like a human without magic?

How could a Lich maintain the appearance of being alive without magic?

Why do unstable nuclei form?

Should these notes be played as a chord or one after another?

Guns in space with bullets that return?

Is there enough time to Planar Bind a creature conjured by a 1-hour-duration spell?

How to pronounce "r" after a "g"?

How did Thanos not realise this had happened at the end of Endgame?

Can the sorting of a list be verified without comparing neighbors?

Ubuntu won't let me edit or delete .vimrc file

Is a diamond sword feasible?

What does i386 mean on macOS Mojave?

Two researchers want to work on the same extension to my paper. Who to help?

How to deal with inappropriate comments during interviews for academic positions?

Why in a Ethernet LAN, a packet sniffer can obtain all packets sent over the LAN?

Can you book a one-way ticket to the UK on a visa?



Why query cache plan kept dynamic queries but not sp?


how to minimize the effect of updating statistics on the plan cache?Is execution plan cached “better” for stored procedures than for a non-dynamic query?Can a plan “age” reach zero?How to regenerate execution plans after clearing the plan cache?Tracking Down Plan Cache ClearingMissing execution plans for stored proceduresSQL Server cached an execution plan which is not optimal in some cases and uses it for all consequent queriesInstant plan cache cleanupPlan cache mysterySQL Buffer Pool and Plan cache






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








4















My company has some legacy system that uses quite a lot of dynamic queries (no parameters). In the newer systems we use Stored Procedures and parameterised SQL. However what we found is that our Stored Procedures frequently got performance spikes.



I looked into it and seems the plan cache periodically clears stored procedure plans, but keeps lots of dynamic SQL statements in the plan cache.



I am bit confused on why SQL Server (SQL Server 2017) is doing this. How does SQL Server decide which one to remove?










share|improve this question






























    4















    My company has some legacy system that uses quite a lot of dynamic queries (no parameters). In the newer systems we use Stored Procedures and parameterised SQL. However what we found is that our Stored Procedures frequently got performance spikes.



    I looked into it and seems the plan cache periodically clears stored procedure plans, but keeps lots of dynamic SQL statements in the plan cache.



    I am bit confused on why SQL Server (SQL Server 2017) is doing this. How does SQL Server decide which one to remove?










    share|improve this question


























      4












      4








      4








      My company has some legacy system that uses quite a lot of dynamic queries (no parameters). In the newer systems we use Stored Procedures and parameterised SQL. However what we found is that our Stored Procedures frequently got performance spikes.



      I looked into it and seems the plan cache periodically clears stored procedure plans, but keeps lots of dynamic SQL statements in the plan cache.



      I am bit confused on why SQL Server (SQL Server 2017) is doing this. How does SQL Server decide which one to remove?










      share|improve this question
















      My company has some legacy system that uses quite a lot of dynamic queries (no parameters). In the newer systems we use Stored Procedures and parameterised SQL. However what we found is that our Stored Procedures frequently got performance spikes.



      I looked into it and seems the plan cache periodically clears stored procedure plans, but keeps lots of dynamic SQL statements in the plan cache.



      I am bit confused on why SQL Server (SQL Server 2017) is doing this. How does SQL Server decide which one to remove?







      sql-server execution-plan plan-cache






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited May 1 at 12:24









      Mark Sinkinson

      8,11033149




      8,11033149










      asked May 1 at 12:23









      daxudaxu

      1303




      1303




















          1 Answer
          1






          active

          oldest

          votes


















          7














          Cached Plans are typically only removed from the plan cache under memory pressure.



          SQL Server primarily considers the cost of the plan when deciding which plans to remove. Lost-cost plans are removed before high-cost plans. The "cost" here is not directly the same as the "plan cost" you see when looking at execution plans - it's a costing mechanism associated with the cache.



          When SQL Server detects memory pressure, it removes zero-cost plans from the cache, then reduces the cost of the remaining plans by 50%. For ad-hoc plans, the cost of the plan is considered to be zero, however that cost is increased by one every time the plan is reused. If you have "optimize for ad-hoc plans" enabled, it's likely the dynamic queries you're seeing in the cache have been heavily used, and as a result have a "high" cache cost, and are not being evicted. For non-ad-hoc plans, the plan cost is not incremented each time a plan is used, but is kept at the original plan cost, which is based on the execution-plan cost. You can see the number of times a particular plan has been used in the sys.dm_exec_cached_plans DMV.



          Cache cost is measured in units known as "ticks", with a maximum of 31. Ticks are incremented according to this:



          1. each I/O adds 1 tick, up to a maximum of 19 ticks.

          2. each context switch adds one tick, up to a maximum of 8 ticks.

          3. one tick per 16 pages of memory, with a maximum of 4 ticks.

          Ticks start to be decremented once the plan cache reaches 50% of its capacity. At that point, SQL Server initiates a resource monitor thread that decrements each plan tick-count by 1 each time the cache is populated with another plan.



          The sys.dm_os_memory_cache_entries DMV contains details about what objects are in the cache, along with the original and current costs, among a number of other useful metrics.



          The details listed above are based on details found in SQL Server Internals by Kalen Delaney.






          share|improve this answer























            Your Answer








            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "182"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: false,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: null,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdba.stackexchange.com%2fquestions%2f237117%2fwhy-query-cache-plan-kept-dynamic-queries-but-not-sp%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            7














            Cached Plans are typically only removed from the plan cache under memory pressure.



            SQL Server primarily considers the cost of the plan when deciding which plans to remove. Lost-cost plans are removed before high-cost plans. The "cost" here is not directly the same as the "plan cost" you see when looking at execution plans - it's a costing mechanism associated with the cache.



            When SQL Server detects memory pressure, it removes zero-cost plans from the cache, then reduces the cost of the remaining plans by 50%. For ad-hoc plans, the cost of the plan is considered to be zero, however that cost is increased by one every time the plan is reused. If you have "optimize for ad-hoc plans" enabled, it's likely the dynamic queries you're seeing in the cache have been heavily used, and as a result have a "high" cache cost, and are not being evicted. For non-ad-hoc plans, the plan cost is not incremented each time a plan is used, but is kept at the original plan cost, which is based on the execution-plan cost. You can see the number of times a particular plan has been used in the sys.dm_exec_cached_plans DMV.



            Cache cost is measured in units known as "ticks", with a maximum of 31. Ticks are incremented according to this:



            1. each I/O adds 1 tick, up to a maximum of 19 ticks.

            2. each context switch adds one tick, up to a maximum of 8 ticks.

            3. one tick per 16 pages of memory, with a maximum of 4 ticks.

            Ticks start to be decremented once the plan cache reaches 50% of its capacity. At that point, SQL Server initiates a resource monitor thread that decrements each plan tick-count by 1 each time the cache is populated with another plan.



            The sys.dm_os_memory_cache_entries DMV contains details about what objects are in the cache, along with the original and current costs, among a number of other useful metrics.



            The details listed above are based on details found in SQL Server Internals by Kalen Delaney.






            share|improve this answer



























              7














              Cached Plans are typically only removed from the plan cache under memory pressure.



              SQL Server primarily considers the cost of the plan when deciding which plans to remove. Lost-cost plans are removed before high-cost plans. The "cost" here is not directly the same as the "plan cost" you see when looking at execution plans - it's a costing mechanism associated with the cache.



              When SQL Server detects memory pressure, it removes zero-cost plans from the cache, then reduces the cost of the remaining plans by 50%. For ad-hoc plans, the cost of the plan is considered to be zero, however that cost is increased by one every time the plan is reused. If you have "optimize for ad-hoc plans" enabled, it's likely the dynamic queries you're seeing in the cache have been heavily used, and as a result have a "high" cache cost, and are not being evicted. For non-ad-hoc plans, the plan cost is not incremented each time a plan is used, but is kept at the original plan cost, which is based on the execution-plan cost. You can see the number of times a particular plan has been used in the sys.dm_exec_cached_plans DMV.



              Cache cost is measured in units known as "ticks", with a maximum of 31. Ticks are incremented according to this:



              1. each I/O adds 1 tick, up to a maximum of 19 ticks.

              2. each context switch adds one tick, up to a maximum of 8 ticks.

              3. one tick per 16 pages of memory, with a maximum of 4 ticks.

              Ticks start to be decremented once the plan cache reaches 50% of its capacity. At that point, SQL Server initiates a resource monitor thread that decrements each plan tick-count by 1 each time the cache is populated with another plan.



              The sys.dm_os_memory_cache_entries DMV contains details about what objects are in the cache, along with the original and current costs, among a number of other useful metrics.



              The details listed above are based on details found in SQL Server Internals by Kalen Delaney.






              share|improve this answer

























                7












                7








                7







                Cached Plans are typically only removed from the plan cache under memory pressure.



                SQL Server primarily considers the cost of the plan when deciding which plans to remove. Lost-cost plans are removed before high-cost plans. The "cost" here is not directly the same as the "plan cost" you see when looking at execution plans - it's a costing mechanism associated with the cache.



                When SQL Server detects memory pressure, it removes zero-cost plans from the cache, then reduces the cost of the remaining plans by 50%. For ad-hoc plans, the cost of the plan is considered to be zero, however that cost is increased by one every time the plan is reused. If you have "optimize for ad-hoc plans" enabled, it's likely the dynamic queries you're seeing in the cache have been heavily used, and as a result have a "high" cache cost, and are not being evicted. For non-ad-hoc plans, the plan cost is not incremented each time a plan is used, but is kept at the original plan cost, which is based on the execution-plan cost. You can see the number of times a particular plan has been used in the sys.dm_exec_cached_plans DMV.



                Cache cost is measured in units known as "ticks", with a maximum of 31. Ticks are incremented according to this:



                1. each I/O adds 1 tick, up to a maximum of 19 ticks.

                2. each context switch adds one tick, up to a maximum of 8 ticks.

                3. one tick per 16 pages of memory, with a maximum of 4 ticks.

                Ticks start to be decremented once the plan cache reaches 50% of its capacity. At that point, SQL Server initiates a resource monitor thread that decrements each plan tick-count by 1 each time the cache is populated with another plan.



                The sys.dm_os_memory_cache_entries DMV contains details about what objects are in the cache, along with the original and current costs, among a number of other useful metrics.



                The details listed above are based on details found in SQL Server Internals by Kalen Delaney.






                share|improve this answer













                Cached Plans are typically only removed from the plan cache under memory pressure.



                SQL Server primarily considers the cost of the plan when deciding which plans to remove. Lost-cost plans are removed before high-cost plans. The "cost" here is not directly the same as the "plan cost" you see when looking at execution plans - it's a costing mechanism associated with the cache.



                When SQL Server detects memory pressure, it removes zero-cost plans from the cache, then reduces the cost of the remaining plans by 50%. For ad-hoc plans, the cost of the plan is considered to be zero, however that cost is increased by one every time the plan is reused. If you have "optimize for ad-hoc plans" enabled, it's likely the dynamic queries you're seeing in the cache have been heavily used, and as a result have a "high" cache cost, and are not being evicted. For non-ad-hoc plans, the plan cost is not incremented each time a plan is used, but is kept at the original plan cost, which is based on the execution-plan cost. You can see the number of times a particular plan has been used in the sys.dm_exec_cached_plans DMV.



                Cache cost is measured in units known as "ticks", with a maximum of 31. Ticks are incremented according to this:



                1. each I/O adds 1 tick, up to a maximum of 19 ticks.

                2. each context switch adds one tick, up to a maximum of 8 ticks.

                3. one tick per 16 pages of memory, with a maximum of 4 ticks.

                Ticks start to be decremented once the plan cache reaches 50% of its capacity. At that point, SQL Server initiates a resource monitor thread that decrements each plan tick-count by 1 each time the cache is populated with another plan.



                The sys.dm_os_memory_cache_entries DMV contains details about what objects are in the cache, along with the original and current costs, among a number of other useful metrics.



                The details listed above are based on details found in SQL Server Internals by Kalen Delaney.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered May 1 at 13:46









                Max VernonMax Vernon

                53.2k13116234




                53.2k13116234



























                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Database Administrators Stack Exchange!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdba.stackexchange.com%2fquestions%2f237117%2fwhy-query-cache-plan-kept-dynamic-queries-but-not-sp%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Club Baloncesto Breogán Índice Historia | Pavillón | Nome | O Breogán na cultura popular | Xogadores | Adestradores | Presidentes | Palmarés | Historial | Líderes | Notas | Véxase tamén | Menú de navegacióncbbreogan.galCadroGuía oficial da ACB 2009-10, páxina 201Guía oficial ACB 1992, páxina 183. Editorial DB.É de 6.500 espectadores sentados axeitándose á última normativa"Estudiantes Junior, entre as mellores canteiras"o orixinalHemeroteca El Mundo Deportivo, 16 setembro de 1970, páxina 12Historia do BreogánAlfredo Pérez, o último canoneiroHistoria C.B. BreogánHemeroteca de El Mundo DeportivoJimmy Wright, norteamericano do Breogán deixará Lugo por ameazas de morteResultados de Breogán en 1986-87Resultados de Breogán en 1990-91Ficha de Velimir Perasović en acb.comResultados de Breogán en 1994-95Breogán arrasa al Barça. "El Mundo Deportivo", 27 de setembro de 1999, páxina 58CB Breogán - FC BarcelonaA FEB invita a participar nunha nova Liga EuropeaCharlie Bell na prensa estatalMáximos anotadores 2005Tempada 2005-06 : Tódolos Xogadores da Xornada""Non quero pensar nunha man negra, mais pregúntome que está a pasar""o orixinalRaúl López, orgulloso dos xogadores, presume da boa saúde económica do BreogánJulio González confirma que cesa como presidente del BreogánHomenaxe a Lisardo GómezA tempada do rexurdimento celesteEntrevista a Lisardo GómezEl COB dinamita el Pazo para forzar el quinto (69-73)Cafés Candelas, patrocinador del CB Breogán"Suso Lázare, novo presidente do Breogán"o orixinalCafés Candelas Breogán firma el mayor triunfo de la historiaEl Breogán realizará 17 homenajes por su cincuenta aniversario"O Breogán honra ao seu fundador e primeiro presidente"o orixinalMiguel Giao recibiu a homenaxe do PazoHomenaxe aos primeiros gladiadores celestesO home que nos amosa como ver o Breo co corazónTita Franco será homenaxeada polos #50anosdeBreoJulio Vila recibirá unha homenaxe in memoriam polos #50anosdeBreo"O Breogán homenaxeará aos seus aboados máis veteráns"Pechada ovación a «Capi» Sanmartín e Ricardo «Corazón de González»Homenaxe por décadas de informaciónPaco García volve ao Pazo con motivo do 50 aniversario"Resultados y clasificaciones""O Cafés Candelas Breogán, campión da Copa Princesa""O Cafés Candelas Breogán, equipo ACB"C.B. Breogán"Proxecto social"o orixinal"Centros asociados"o orixinalFicha en imdb.comMario Camus trata la recuperación del amor en 'La vieja música', su última película"Páxina web oficial""Club Baloncesto Breogán""C. B. Breogán S.A.D."eehttp://www.fegaba.com

                    Vilaño, A Laracha Índice Patrimonio | Lugares e parroquias | Véxase tamén | Menú de navegación43°14′52″N 8°36′03″O / 43.24775, -8.60070

                    Cegueira Índice Epidemioloxía | Deficiencia visual | Tipos de cegueira | Principais causas de cegueira | Tratamento | Técnicas de adaptación e axudas | Vida dos cegos | Primeiros auxilios | Crenzas respecto das persoas cegas | Crenzas das persoas cegas | O neno deficiente visual | Aspectos psicolóxicos da cegueira | Notas | Véxase tamén | Menú de navegación54.054.154.436928256blindnessDicionario da Real Academia GalegaPortal das Palabras"International Standards: Visual Standards — Aspects and Ranges of Vision Loss with Emphasis on Population Surveys.""Visual impairment and blindness""Presentan un plan para previr a cegueira"o orixinalACCDV Associació Catalana de Cecs i Disminuïts Visuals - PMFTrachoma"Effect of gene therapy on visual function in Leber's congenital amaurosis"1844137110.1056/NEJMoa0802268Cans guía - os mellores amigos dos cegosArquivadoEscola de cans guía para cegos en Mortágua, PortugalArquivado"Tecnología para ciegos y deficientes visuales. Recopilación de recursos gratuitos en la Red""Colorino""‘COL.diesis’, escuchar los sonidos del color""COL.diesis: Transforming Colour into Melody and Implementing the Result in a Colour Sensor Device"o orixinal"Sistema de desarrollo de sinestesia color-sonido para invidentes utilizando un protocolo de audio""Enseñanza táctil - geometría y color. Juegos didácticos para niños ciegos y videntes""Sistema Constanz"L'ocupació laboral dels cecs a l'Estat espanyol està pràcticament equiparada a la de les persones amb visió, entrevista amb Pedro ZuritaONCE (Organización Nacional de Cegos de España)Prevención da cegueiraDescrición de deficiencias visuais (Disc@pnet)Braillín, un boneco atractivo para calquera neno, con ou sen discapacidade, que permite familiarizarse co sistema de escritura e lectura brailleAxudas Técnicas36838ID00897494007150-90057129528256DOID:1432HP:0000618D001766C10.597.751.941.162C97109C0155020