{"id":2565,"date":"2021-08-04T16:38:34","date_gmt":"2021-08-04T16:38:34","guid":{"rendered":"https:\/\/manualsqlserver.com\/?p=2565"},"modified":"2021-08-04T16:38:36","modified_gmt":"2021-08-04T16:38:36","slug":"cursores-y-pivot-en-sql-server","status":"publish","type":"post","link":"https:\/\/manualsqlserver.com\/?p=2565","title":{"rendered":"Cursores y Pivot en SQL Server"},"content":{"rendered":"\n<figure class=\"wp-block-image size-full\"><a href=\"https:\/\/manualsqlserver.com\/wp-content\/uploads\/2021\/08\/ManualSQL_CursoresPivot__D.png\"><img loading=\"lazy\" decoding=\"async\" width=\"220\" height=\"260\" src=\"https:\/\/manualsqlserver.com\/wp-content\/uploads\/2021\/08\/ManualSQL_CursoresPivot__D.png\" alt=\"\" class=\"wp-image-2566\"\/><\/a><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Cursores y Pivot en SQL Server<\/strong><\/h2>\n\n\n\n<p>En este art\u00edculo se utiliza un cursor para mostrar las ventas de los productos en un a\u00f1o determinado, siempre se recomienda usar con cuidado los cursores, estos consumen recursos importantes en el servidor, siempre que use un cursor eval\u00fae usar si es posible otras opciones, adem\u00e1s de que la instrucci\u00f3n Select del cursor tenga solamente<br>los campos necesarios y los filtros adecuados.<\/p>\n\n\n\n<!--more-->\n\n\n\n<p>En este art\u00edculo usamos una CTE (Common Table Expression) y usamos Pivot para mostrar las compras por mes y totalizarlas en una \u00faltima columna durante el a\u00f1o 1997, puede usar procedimientos almacenados para poder dinamizar el resultado del cursor para cualquier a\u00f1o.<\/p>\n\n\n\n<p class=\"has-large-font-size\"><strong>Para mas informaci\u00f3n ver<br><\/strong><a href=\"https:\/\/manualsqlserver.com\/\" target=\"_blank\" rel=\"noreferrer noopener\">Cursores en SQL Server<\/a><br><a href=\"https:\/\/manualsqlserver.com\/?p=507\" target=\"_blank\" rel=\"noreferrer noopener\">Pivot en SQL Server<\/a><br><a href=\"https:\/\/manualsqlserver.com\/?p=514\" target=\"_blank\" rel=\"noreferrer noopener\">CTE en SQL Server<\/a><br><a href=\"https:\/\/manualsqlserver.com\/?p=225\" target=\"_blank\" rel=\"noreferrer noopener\">Agrupamientos<\/a><br><a href=\"https:\/\/manualsqlserver.com\/?p=522\" target=\"_blank\" rel=\"noreferrer noopener\">Variables tipo tabla<\/a><\/p>\n\n\n\n<p style=\"font-size:24px\"><strong>Ejercicio<\/strong><\/p>\n\n\n\n<p>El ejercicio muestra los productos y la cantidad de unidades vendidas en 1997, mostrando el detalle de cada mes.<\/p>\n\n\n\n<pre class=\"wp-block-code\" style=\"font-size:12px\"><code>use Northwind\r\ngo\r\nset dateformat dmy\r\ngo\r\nDeclare  cursorVentasAnuales  cursor  for\r\n\twith TotalVentas As\r\n\t\t(\r\n\t\t\tSELECT \r\n\t\t\t\tP.ProductName As 'Producto', \r\n\t\t\t\tMONTH(O.OrderDate) As  'Mes',\r\n\t\t\t\tSUM(D.Quantity) As 'Unidades'\r\n\t\t\tfrom Products As P\r\n\t\t\t\tjoin &#91;Order Details]  As D on P.ProductID = D.ProductID\r\n\t\t\t\tjoin Orders As O on D.OrderID = O.OrderID\r\n\t\t\t\tWhere O.OrderDate between '01\/01\/1997' and '31\/12\/1997'\r\n\t\t\tGROUP BY P.ProductName, MONTH(O.OrderDate)\r\n\t\t)\r\n\t\tselect \r\n\t\t\tProducto, ISNULL(&#91;1],0) Ene, ISNULL(&#91;2],0) Feb, \r\n\t\t\t\tISNULL(&#91;3],0) Mar, ISNULL(&#91;4],0) Abr, ISNULL(&#91;5],0) May,\r\n\t\t\t\tISNULL(&#91;6],0) Jun, ISNULL(&#91;7],0) Jul, ISNULL(&#91;8],0) Ago,\r\n\t\t\t\tISNULL(&#91;9],0) Sep, ISNULL(&#91;10],0) Oct, ISNULL(&#91;11],0) Nov, \r\n\t\t\t\tISNULL(&#91;12],0) Dic\r\n\t\t\tfrom TotalVentas\r\n\t\t\tPivot (SUM(Unidades) \r\n\t\t\tfor Mes in (&#91;1], &#91;2], &#91;3], &#91;4], &#91;5], &#91;6], &#91;7], &#91;8], &#91;9], &#91;10], &#91;11], &#91;12]))\r\n\t\t\tAs Tabla\r\nOpen cursorVentasAnuales\r\nDeclare @VentasAnualesProducto table\r\n\t(\r\n\tNombre nvarchar(50), Enero Numeric(9,2), Febrero Numeric(9,2),Marzo Numeric(9,2), Abril Numeric(9,2),\r\n\tMayo Numeric(9,2), Junio Numeric(9,2), Julio Numeric(9,2), Agosto Numeric(9,2), Septiembre Numeric(9,2),\r\n\tOctubre Numeric(9,2), Noviembre Numeric(9,2), Diciembre Numeric(9,2), Total Numeric(9,2)\r\n\t)\r\nDeclare @Nombre nvarchar(50), @Enero Numeric(9,2), @Febrero Numeric(9,2),@Marzo Numeric(9,2), @Abril Numeric(9,2),\r\n\t@Mayo Numeric(9,2), @Junio Numeric(9,2), @Julio Numeric(9,2), @Agosto Numeric(9,2), @Septiembre Numeric(9,2),\r\n\t@Octubre Numeric(9,2), @Noviembre Numeric(9,2), @Diciembre Numeric(9,2), @Total Numeric(9,2)\r\nFetch cursorVentasAnuales into \r\n\t@Nombre , @Enero , @Febrero ,@Marzo , @Abril ,\r\n\t@Mayo , @Junio , @Julio , @Agosto , @Septiembre ,\r\n\t@Octubre , @Noviembre , @Diciembre \r\n\twhile (@@FETCH_STATUS = 0)\r\n\t\tBegin\r\n\t\t\tSet @Total = ( @Enero + @Febrero +@Marzo + @Abril +\r\n\t\t\t\t@Mayo + @Junio + @Julio + @Agosto + @Septiembre +\r\n\t\t\t\t@Octubre + @Noviembre + @Diciembre )\r\n\t\t\tinsert into @VentasAnualesProducto \r\n\t\t\t\t(Nombre , Enero , Febrero ,Marzo , Abril,\r\n\t\t\t\tMayo , Junio , Julio , Agosto , Septiembre ,\r\n\t\t\t\tOctubre, Noviembre , Diciembre , Total)\r\n\t\t\t\tvalues \r\n\t\t\t\t(@Nombre , @Enero , @Febrero ,@Marzo , @Abril ,\r\n\t\t\t\t@Mayo , @Junio , @Julio , @Agosto , @Septiembre ,\r\n\t\t\t\t@Octubre , @Noviembre , @Diciembre, @Total)\r\n\t\t\tFetch cursorVentasAnuales into \r\n\t\t\t\t@Nombre , @Enero , @Febrero ,@Marzo , @Abril ,\r\n\t\t\t\t@Mayo , @Junio , @Julio , @Agosto , @Septiembre ,\r\n\t\t\t\t@Octubre , @Noviembre , @Diciembre \r\n\t\tEnd\r\nclose cursorVentasAnuales\r\nDeallocate cursorVentasAnuales\r\nselect * from @VentasAnualesProducto\r\ngo<\/code><\/pre>\n\n\n\n<p>La imagen muestra el resultado<\/p>\n\n\n\n<figure class=\"wp-block-image size-large is-resized\"><a href=\"https:\/\/manualsqlserver.com\/wp-content\/uploads\/2021\/08\/ManualSQL_CursoresPivot_01.png\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/manualsqlserver.com\/wp-content\/uploads\/2021\/08\/ManualSQL_CursoresPivot_01-1024x574.png\" alt=\"\" class=\"wp-image-2567\" width=\"834\" height=\"467\" srcset=\"https:\/\/manualsqlserver.com\/wp-content\/uploads\/2021\/08\/ManualSQL_CursoresPivot_01-1024x574.png 1024w, https:\/\/manualsqlserver.com\/wp-content\/uploads\/2021\/08\/ManualSQL_CursoresPivot_01-300x168.png 300w, https:\/\/manualsqlserver.com\/wp-content\/uploads\/2021\/08\/ManualSQL_CursoresPivot_01-768x430.png 768w, https:\/\/manualsqlserver.com\/wp-content\/uploads\/2021\/08\/ManualSQL_CursoresPivot_01-795x445.png 795w, https:\/\/manualsqlserver.com\/wp-content\/uploads\/2021\/08\/ManualSQL_CursoresPivot_01.png 1276w\" sizes=\"auto, (max-width: 834px) 100vw, 834px\" \/><\/a><\/figure>\n\n\n\n<script async=\"\" src=\"\/\/pagead2.googlesyndication.com\/pagead\/js\/adsbygoogle.js\"><\/script>\n<ins class=\"adsbygoogle\" style=\"display:block; text-align:center;\" data-ad-layout=\"in-article\" data-ad-format=\"fluid\" data-ad-client=\"ca-pub-2636008503986218\" data-ad-slot=\"1902193434\"><\/ins>\n<script>\n     (adsbygoogle = window.adsbygoogle || []).push({});\n<\/script<\/script>\n","protected":false},"excerpt":{"rendered":"<p>Cursores y Pivot en SQL Server En este art\u00edculo se utiliza un cursor para mostrar las ventas de los productos en un a\u00f1o determinado, siempre se recomienda usar con cuidado los cursores, estos consumen recursos importantes en el servidor, siempre que use un cursor eval\u00fae usar si es posible otras opciones, adem\u00e1s de que la &hellip; <\/p>\n<p><a class=\"more-link btn\" href=\"https:\/\/manualsqlserver.com\/?p=2565\">Seguir leyendo<\/a><\/p>\n","protected":false},"author":1,"featured_media":2566,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[232],"tags":[25,48,171],"class_list":["post-2565","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-cursoressql","tag-cursores","tag-pivot","tag-variable-tipo-tabla","nodate","item-wrap"],"_links":{"self":[{"href":"https:\/\/manualsqlserver.com\/index.php?rest_route=\/wp\/v2\/posts\/2565","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/manualsqlserver.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/manualsqlserver.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/manualsqlserver.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/manualsqlserver.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=2565"}],"version-history":[{"count":1,"href":"https:\/\/manualsqlserver.com\/index.php?rest_route=\/wp\/v2\/posts\/2565\/revisions"}],"predecessor-version":[{"id":2569,"href":"https:\/\/manualsqlserver.com\/index.php?rest_route=\/wp\/v2\/posts\/2565\/revisions\/2569"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/manualsqlserver.com\/index.php?rest_route=\/wp\/v2\/media\/2566"}],"wp:attachment":[{"href":"https:\/\/manualsqlserver.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=2565"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/manualsqlserver.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=2565"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/manualsqlserver.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=2565"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}