<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>glufke.net &#187; Utilidade</title>
	<atom:link href="http://glufke.net/tag/utilidade/feed/" rel="self" type="application/rss+xml" />
	<link>http://glufke.net</link>
	<description></description>
	<lastBuildDate>Mon, 16 Apr 2012 19:33:42 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Fazendo Rateio através de Funções Analíticas</title>
		<link>http://glufke.net/2012/04/11/fazendo-rateio-atraves-de-funcoes-analiticas/</link>
		<comments>http://glufke.net/2012/04/11/fazendo-rateio-atraves-de-funcoes-analiticas/#comments</comments>
		<pubDate>Wed, 11 Apr 2012 20:43:50 +0000</pubDate>
		<dc:creator>glufke</dc:creator>
				<category><![CDATA[SQL]]></category>
		<category><![CDATA[Analíticas]]></category>
		<category><![CDATA[Funções]]></category>
		<category><![CDATA[Matemática]]></category>
		<category><![CDATA[Rateio]]></category>
		<category><![CDATA[Utilidade]]></category>

		<guid isPermaLink="false">http://glufke.net/?p=508</guid>
		<description><![CDATA[
			
			
			
			
			
			
			
						
			Neste post, vamos mostrar como utilizar funções analíticas para fazer o rateio de um valor em diversas linhas de uma tabela.
Primeiro, vamos criar a tabela de teste:
CREATE TABLE glufke_teste
(nro_nota  NUMBER, item NUMBER, valor NUMBER);
INSERT INTO glufke_teste VALUES ( 50, 1, 1.45);
INSERT INTO glufke_teste VALUES ( 50, 2, 3.91);
INSERT INTO glufke_teste VALUES ( 50, 3, [...]]]></description>
			<content:encoded><![CDATA[<div class="bottomcontainerBox" style="">
			<div style="float:left; width:50px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;">
			<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fglufke.net%2F2012%2F04%2F11%2Ffazendo-rateio-atraves-de-funcoes-analiticas%2F&amp;layout=button_count&amp;show_faces=false&amp;width=50&amp;action=like&amp;font=verdana&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" allowTransparency="true" style="border:none; overflow:hidden; width:50px; height:21px;"></iframe></div>
			<div style="float:left; width:60px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;">
			<g:plusone size="medium" href="http://glufke.net/2012/04/11/fazendo-rateio-atraves-de-funcoes-analiticas/"></g:plusone>
			</div>
			<div style="float:left; width:70px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;">
			<a href="http://twitter.com/share" class="twitter-share-button" data-url="http://glufke.net/2012/04/11/fazendo-rateio-atraves-de-funcoes-analiticas/"  data-text="Fazendo Rateio através de Funções Analíticas" data-count="horizontal" data-via="glufke"></a>
			</div><div style="float:left; width:110px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script type="in/share" data-url="http://glufke.net/2012/04/11/fazendo-rateio-atraves-de-funcoes-analiticas/" data-counter="right"></script></div>			
			</div><div style="clear:both"></div><div style="padding-bottom:4px;"></div><p><a href="http://glufke.net/wp-content/uploads/2012/04/rateio.jpg"><img class="size-full wp-image-533 alignright" title="Rateio" src="http://glufke.net/wp-content/uploads/2012/04/rateio.jpg" alt="" width="89" height="90" /></a>Neste post, vamos mostrar como utilizar <strong>funções analíticas</strong> para fazer o rateio de um valor em diversas linhas de uma tabela.</p>
<p>Primeiro, vamos criar a tabela de teste:</p>
<pre class="brush: sql;">CREATE TABLE glufke_teste
(nro_nota  NUMBER, item NUMBER, valor NUMBER);
INSERT INTO glufke_teste VALUES ( 50, 1, 1.45);
INSERT INTO glufke_teste VALUES ( 50, 2, 3.91);
INSERT INTO glufke_teste VALUES ( 50, 3, 5.04);</pre>
<pre class="brush: plain;">SQL&gt; SELECT * FROM glufke_teste;

  NRO_NOTA       ITEM      VALOR
---------- ---------- ----------
        50          1       1,45
        50          2       3,91
        50          3       5,04

SQL&gt;</pre>
<p>Nosso objetivo é ratear um valor proporcionalmente nessas linhas. Como exemplo prático, vamos distribuir o valor R$ 49,30!<span id="more-508"></span></p>
<div id="ads_336x280"><script type="text/javascript">// <![CDATA[
    google_ad_client = "pub-8964513116661040"; google_alternate_color = "ffffFF"; google_ad_width = 336; google_ad_height = 280; google_ad_format = "336x280_as"; google_ad_type = "text_image"; //2007-09-07: wp_quadrado_gra google_ad_channel = "0247072216"; google_color_border = "FFFFFF"; google_color_bg = "FFFFff"; google_color_link = "4F82CB"; google_color_text = "000000"; google_color_url = "4F82CB";
// ]]&gt;</script><script src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript">
</script></div>
<p>Sabemos que a soma das 3 linhas é 10,40:</p>
<pre class="brush: plain;">SQL&gt; SELECT SUM(VALOR) FROM GLUFKE_TESTE;

SUM(VALOR)
----------
      10,4

SQL&gt;</pre>
<p>Então, através de uma simples regra de 3, vemos o percentual de cada linha! Ou seja, temos que aplicar o valor de 49,30 conforme esses percentuais!</p>
<pre class="brush: plain;">SQL&gt; SELECT VALOR, VALOR/10.4*100 PERC FROM GLUFKE_TESTE;

     VALOR       PERC
---------- ----------
      1,45 13,9423076
      3,91 37,5961538
      5,04 48,4615384

SQL&gt;</pre>
<p>Com isso, basta colocar o valor 49.30 ali que temos distribuído! Repare que a soma do valor rateado é exatamente os 49,30 ! Ou seja, está distribuído conforme nossa necessidade!</p>
<pre class="brush: plain;">SQL&gt; select valor, valor/10.4* 49.3 vlr_rateado from glufke_teste;

     VALOR VLR_RATEADO
---------- -----------
      1,45 6,873557692
      3,91 18,53490384
      5,04 23,89153846

SQL&gt;</pre>
<h3>Usando funções analíticas pra obter esse resultado!</h3>
<p>Agora, usando a função analitica SUM, pra buscar &#8220;em tempo de execução&#8221; a soma da coluna valor (abaixo, a coluna TOTAL), e fazer o cálculo todo numa única tacada!</p>
<pre class="brush: sql;">SELECT
  nro_nota
, item
, valor
, sum(valor) over (order by nro_nota) total
, valor / sum(valor) over (order by nro_nota) * 49.3 vlr_rateado
FROM GLUFKE_teste
WHERE nro_nota = 50
/</pre>
<pre class="brush: plain;">  NRO_NOTA       ITEM      VALOR      TOTAL VLR_RATEADO
---------- ---------- ---------- ---------- -----------
        50          1       1,45       10,4 6,873557692
        50          2       3,91       10,4 18,53490384
        50          3       5,04       10,4 23,89153846

SQL></pre>
<p>Vamos adicionar mais um campo chamado VLR_RATEADO, que arredonda pra 2 casas decimais o valor:</p>
<pre class="brush: sql;">SELECT
  nro_nota
, item
, valor
, sum(valor) over (order by nro_nota) total
, valor / sum(valor) over (order by nro_nota) * 50 vlr_rateado
, ROUND(   valor / sum(valor) over (order by nro_nota) * 49.3 ,2 ) vlr_arr
FROM glufke_teste
WHERE nro_nota = 50
/</pre>
<pre class="brush: plain;">  NRO_NOTA       ITEM      VALOR      TOTAL VLR_RATEADO VLR_ARR
---------- ---------- ---------- ---------- ----------- -----------
        50          1       1,45       10,4 6,971153846        6,87
        50          2       3,91       10,4 18,79807692       18,53
        50          3       5,04       10,4 24,23076923       23,89

SQL&gt;</pre>
<p><strong>PROBLEMA A VISTA!</strong><br />
Quando fazemos rateios e arredondamos o valor, a chance de dar uma diferença de 1 centavo ou mais é muito grande! Se somarmos o valor rateado <em>não fecha com os 49.3</em>!</p>
<p>Veja:   6.87 + 18.53 + 23.89 = 49.29 !!! (diferença de 1 centavo!)</p>
<h3>Resolvendo problema do centavo</h3>
<p>Vamos usar funções analíticas pra jogar essa diferença de 1 centavo para uma das linhas da nota! (no caso, vamos jogar para a linha de maior valor).</p>
<p>Primeiro, vamos descobrir se realmente existe uma diferença de 1 centavo ou mais:</p>
<pre class="brush: sql;">
SELECT
  VLR_RATEADO
, ROUND(VLR_RATEADO,2)                        VLR_ARR
, COUNT(1) OVER (ORDER BY 1)                  QTD_LIN
, ROW_NUMBER()    OVER (ORDER BY VLR_RATEADO) LIN
, SUM(VLR_RATEADO) OVER (ORDER BY 1)          SOMA
, SUM(ROUND(VLR_RATEADO,2)) OVER (ORDER BY 1) SOMA_ARR
FROM
(
 SELECT
   nro_nota
 , item
 , valor
 , valor / SUM(valor) OVER (ORDER BY nro_nota) * 49.3 vlr_rateado
 FROM glufke_teste
 WHERE nro_nota = 50
 )
/</pre>
<pre class="brush: plain;">VLR_RATEADO    VLR_ARR    QTD_LIN        LIN       SOMA   SOMA_ARR
----------- ---------- ---------- ---------- ---------- ----------
6,873557692       6,87          3          1       49,3      49,29
18,53490384      18,53          3          2       49,3      49,29
23,89153846      23,89          3          3       49,3      49,29

SQL></pre>
<p>Acima, as colunas QTD_LIN e LIN vão nos ser úteis pra aplicar a diferença apenas na última linha, ou seja, quando QTD_LIN = LIN  (no caso 3=3).<br />
A coluna SOMA, contém o valor total.<br />
A coluna SOMA_ARR é a soma do valor arredondado! Repare que tem 1 centavo a menos!</p>
<p>Então, basta fazer um DECODE que aplica essa diferença (49.3 &#8211; 49.2 &#8211;&gt;  SOMA &#8211; SOMA_ARR )<br />
Veja:</p>
<pre class="brush: sql;">
SELECT
  VLR_RATEADO
, ROUND(VLR_RATEADO,2) VLR_RATEADO_ARR
, DECODE( COUNT( 1) OVER (ORDER BY 1)
       , ROW_NUMBER()    OVER (ORDER BY VLR_RATEADO)
       , SUM( VLR_RATEADO) OVER (ORDER BY 1) - SUM( ROUND(VLR_RATEADO,2)) OVER (ORDER BY 1)+ ROUND(VLR_RATEADO,2)
       , ROUND(VLR_RATEADO,2)
       )  VLR_COM_DIF
FROM
(
SELECT
  nro_nota
, item
, valor
, (valor) / SUM(valor) OVER (ORDER BY nro_nota) * 49.3 vlr_rateado
FROM GLUFKE_teste
WHERE nro_nota = 50
)
/</pre>
<pre class="brush: plain;">VLR_RATEADO VLR_RATEADO_ARR VLR_COM_DIF
----------- --------------- -----------
6,873557692            6,87        6,87
18,53490384           18,53       18,53
23,89153846           23,89       23,90

SQL></pre>
<p>O select acima, aplica a diferença de 1 centavo apenas na ultima linha. Dessa forma, a diferença de centavo vai pra uma das linhas e o total rateado sempre fecha corretamente!<br />
A soma do VLR_RATEADO está errada! ( 6,87 + 18,53 + 23,89 = 49,29)<br />
Já o campo VLR_COM_DIF está com a soma correta, fechando os 49,30 !</p>
<p>Dessa forma, com apenas 1 select foi possível realizar o rateio e ainda aplicar a diferença do arredondamento em uma das linhas, graças as funções analíticas!</p>
<h3>Outro Exemplo:</h3>
<pre class="brush: sql;">INSERT INTO glufke_teste VALUES ( 51, 1, 5);
INSERT INTO glufke_teste VALUES ( 51, 2, 5);
INSERT INTO glufke_teste VALUES ( 51, 3, 5);
INSERT INTO glufke_teste VALUES ( 51, 4, 7.5);
INSERT INTO glufke_teste VALUES ( 51, 5, 7.5);</pre>
<p>Vamos aplicar o valor 10 nesses valores:</p>
<pre class="brush: sql;">SELECT
  NRO_NOTA
, ITEM
, VALOR
, ROUND(VLR_RATEADO,2) VLR_RATEADO_ARR
, DECODE( COUNT( 1) OVER (ORDER BY 1)
       , ROW_NUMBER()    OVER (ORDER BY VLR_RATEADO)
       , SUM( VLR_RATEADO) OVER (ORDER BY 1)
       - SUM( ROUND(VLR_RATEADO,2)) OVER (ORDER BY 1)
       + ROUND(VLR_RATEADO,2)
       , ROUND(VLR_RATEADO,2)
       )  VLR_COM_DIF
FROM
(
SELECT
  nro_nota
, item
, valor
, (valor) / SUM(valor) OVER (ORDER BY nro_nota) * 10 vlr_rateado
FROM GLUFKE_teste
WHERE nro_nota = 51
)</pre>
<pre class="brush: plain;">  NRO_NOTA       ITEM      VALOR VLR_RATEADO_ARR VLR_COM_DIF
---------- ---------- ---------- --------------- -----------
        51          1          5            1,67        1,67
        51          2          5            1,67        1,67
        51          3          5            1,67        1,67
        51          4        7,5            2,50        2,50
        51          5        7,5            2,50        2,49

SQL&gt;</pre>
<p>Para terminar a saga, vamos adicionar a palavra-chave PARTITION BY, e dessa forma, podemos fazer o calculo acima para todas as notas! No exemplo abaixo, vamos ratear o valor 10 pra cada nota. Ou seja, no total, a soma vai dar 20, pois temos apenas 2 notas no exemplo:</p>
<pre class="brush: sql;">SELECT
  NRO_NOTA
, ITEM
, VALOR
, ROUND(VLR_RATEADO,2) VLR_RATEADO_ARR
, DECODE( COUNT( 1) OVER (partition by nro_nota  ORDER BY 1)
       , ROW_NUMBER()    OVER (partition by nro_nota ORDER BY VLR_RATEADO)
       , SUM( VLR_RATEADO) OVER (partition by nro_nota ORDER BY 1)
       - SUM( ROUND(VLR_RATEADO,2)) OVER (partition by nro_nota ORDER BY 1)
       + ROUND(VLR_RATEADO,2)
       , ROUND(VLR_RATEADO,2)
       )  VLR_COM_DIF
FROM
(
SELECT
  nro_nota
, item
, valor
, (valor) / SUM(valor) OVER (partition by nro_nota ORDER BY nro_nota) * 10 vlr_rateado
FROM GLUFKE_teste
)</pre>
<pre class="brush: plain;">  NRO_NOTA       ITEM      VALOR VLR_RATEADO_ARR VLR_COM_DIF
---------- ---------- ---------- --------------- -----------
        50          1       1,45            1,39        1,39
        50          2       3,91            3,76        3,76
        50          3       5,04            4,85        4,85
        51          1       5,00            1,67        1,67
        51          3       5,00            1,67        1,67
        51          2       5,00            1,67        1,67
        51          5       7,50            2,50        2,50
        51          4       7,50            2,50        2,49

8 rows selected

SQL> </pre>
<p>Observe que a soma da coluna VLR_COM_DIF fecha exatamente os 20. Ja a coluna VLR_RATEADO_ARR dá diferença de centavo!   </p>
<p>Neste <a href="http://glufke.net/oracle/download/funcoes_ANALITICAS.html">LINK</a> tem diversos exemplos muito bons! Até mais!</p>
]]></content:encoded>
			<wfw:commentRss>http://glufke.net/2012/04/11/fazendo-rateio-atraves-de-funcoes-analiticas/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Transformar linhas do SQL em string delimitada</title>
		<link>http://glufke.net/2007/09/12/transformar-linhas-do-sql-em-string-delimitada/</link>
		<comments>http://glufke.net/2007/09/12/transformar-linhas-do-sql-em-string-delimitada/#comments</comments>
		<pubDate>Wed, 12 Sep 2007 20:02:00 +0000</pubDate>
		<dc:creator>glufke</dc:creator>
				<category><![CDATA[PL/SQL]]></category>
		<category><![CDATA[String]]></category>
		<category><![CDATA[Utilidade]]></category>

		<guid isPermaLink="false">http://glufke.net/2007/09/12/transformar-linhas-do-sql-em-string-delimitada/</guid>
		<description><![CDATA[
			
			
			
			
			
			
			
						
			Essa procedure pode ser muito útil em algumas situações: Ela pega as linhas de uma coluna e retorna cada linha separada por ví­rgula na mesma string. 
CREATE OR REPLACE FUNCTION rowtocol (
   p_slct IN VARCHAR2,
   p_dlmtr IN VARCHAR2 DEFAULT ',' ) RETURN VARCHAR2 AUTHID CURRENT_USER
AS
   TYPE c_refcur IS REF [...]]]></description>
			<content:encoded><![CDATA[<div class="bottomcontainerBox" style="">
			<div style="float:left; width:50px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;">
			<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fglufke.net%2F2007%2F09%2F12%2Ftransformar-linhas-do-sql-em-string-delimitada%2F&amp;layout=button_count&amp;show_faces=false&amp;width=50&amp;action=like&amp;font=verdana&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" allowTransparency="true" style="border:none; overflow:hidden; width:50px; height:21px;"></iframe></div>
			<div style="float:left; width:60px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;">
			<g:plusone size="medium" href="http://glufke.net/2007/09/12/transformar-linhas-do-sql-em-string-delimitada/"></g:plusone>
			</div>
			<div style="float:left; width:70px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;">
			<a href="http://twitter.com/share" class="twitter-share-button" data-url="http://glufke.net/2007/09/12/transformar-linhas-do-sql-em-string-delimitada/"  data-text="Transformar linhas do SQL em string delimitada" data-count="horizontal" data-via="glufke"></a>
			</div><div style="float:left; width:110px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script type="in/share" data-url="http://glufke.net/2007/09/12/transformar-linhas-do-sql-em-string-delimitada/" data-counter="right"></script></div>			
			</div><div style="clear:both"></div><div style="padding-bottom:4px;"></div><p>Essa procedure pode ser muito útil em algumas situações: Ela pega as linhas de uma coluna e retorna cada linha separada por ví­rgula na mesma string. <span id="more-14"></span></p>
<pre class="brush: sql;">CREATE OR REPLACE FUNCTION rowtocol (
   p_slct IN VARCHAR2,
   p_dlmtr IN VARCHAR2 DEFAULT ',' ) RETURN VARCHAR2 AUTHID CURRENT_USER
AS
   TYPE c_refcur IS REF CURSOR;
   lc_str VARCHAR2(4000);
   lc_colval VARCHAR2(4000);
   c_dummy c_refcur;
   l number;
BEGIN
   OPEN c_dummy FOR p_slct;
   LOOP
     FETCH c_dummy INTO lc_colval;
     EXIT WHEN c_dummy%NOTFOUND;
     lc_str := lc_str || p_dlmtr || lc_colval;
   END LOOP;
   CLOSE c_dummy;
   RETURN SUBSTR(lc_str,2);
END;
</pre>
<div id="ads_336x280"><script type="text/javascript"><!--
google_ad_client = "pub-8964513116661040";
google_alternate_color = "ffffFF";
google_ad_width = 336;
google_ad_height = 280;
google_ad_format = "336x280_as";
google_ad_type = "text_image";
//2007-09-07: wp_quadrado_gra
google_ad_channel = "0247072216";
google_color_border = "FFFFFF";
google_color_bg = "FFFFff";
google_color_link = "4F82CB";
google_color_text = "000000";
google_color_url = "4F82CB";
//-->
</script><script type="text/javascript"
  src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<p>Agora vamos ao exemplo:</p>
<pre class="brush: sql;">SQL> CREATE OR REPLACE FUNCTION rowtocol (
  2     p_slct IN VARCHAR2,
  3     p_dlmtr IN VARCHAR2 DEFAULT ',' )
  4  RETURN VARCHAR2
  5     AUTHID CURRENT_USER AS
  6     TYPE c_refcur IS REF CURSOR;
  7     lc_str VARCHAR2(4000);
  8     lc_colval VARCHAR2(4000);
  9     c_dummy c_refcur;
 10     l number;
 11  BEGIN
 12     OPEN c_dummy FOR p_slct;
 13     LOOP
 14       FETCH c_dummy INTO lc_colval;
 15       EXIT WHEN c_dummy%NOTFOUND;
 16       lc_str := lc_str || p_dlmtr || lc_colval;
 17     END LOOP;
 18     CLOSE c_dummy;
 19     RETURN SUBSTR(lc_str,2);
 20  END;
 21  /

Function created.

SQL> SELECT ROWTOCOL('SELECT ENAME FROM EMP') FROM DUAL;

ROWTOCOL('SELECTENAMEFROMEMP')
------------------------------------------------------------------
SMITE,ALLEN,WARD,JONES,MARTIN,BLAKE,SCOTT,TURNER,ADAMS,JAMES,FORD

SQL></pre>
<p>Comente <a href="http://glufke.net/oracle/viewtopic.php?t=31">aqui</a></p>
]]></content:encoded>
			<wfw:commentRss>http://glufke.net/2007/09/12/transformar-linhas-do-sql-em-string-delimitada/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Como descobrir a versão do Oracle</title>
		<link>http://glufke.net/2007/08/22/como-descobrir-a-versao-do-oracle/</link>
		<comments>http://glufke.net/2007/08/22/como-descobrir-a-versao-do-oracle/#comments</comments>
		<pubDate>Wed, 22 Aug 2007 23:34:43 +0000</pubDate>
		<dc:creator>glufke</dc:creator>
				<category><![CDATA[DBA]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[Utilidade]]></category>

		<guid isPermaLink="false">http://glufke.net/2007/08/22/como-descobrir-a-versao-do-oracle/</guid>
		<description><![CDATA[
			
			
			
			
			
			
			
						
			Existem várias formas de descobrir a versão do Oracle sem olhar a &#8220;telinha inicial&#8221; do SQL*Plus. Neste artigo, debateremos 4 maneiras de se descobrir isso. Algumas são bem conhecidas e outra bem &#8220;raras&#8221; de se ver.
Usar a V$Version
SQL> select * from v$version;

BANNER
----------------------------------------------------------------
Oracle9i Enterprise Edition Release 9.0.1.4.0 - Production
PL/SQL Release 9.0.1.4.0 - Production
CORE    [...]]]></description>
			<content:encoded><![CDATA[<div class="bottomcontainerBox" style="">
			<div style="float:left; width:50px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;">
			<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fglufke.net%2F2007%2F08%2F22%2Fcomo-descobrir-a-versao-do-oracle%2F&amp;layout=button_count&amp;show_faces=false&amp;width=50&amp;action=like&amp;font=verdana&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" allowTransparency="true" style="border:none; overflow:hidden; width:50px; height:21px;"></iframe></div>
			<div style="float:left; width:60px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;">
			<g:plusone size="medium" href="http://glufke.net/2007/08/22/como-descobrir-a-versao-do-oracle/"></g:plusone>
			</div>
			<div style="float:left; width:70px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;">
			<a href="http://twitter.com/share" class="twitter-share-button" data-url="http://glufke.net/2007/08/22/como-descobrir-a-versao-do-oracle/"  data-text="Como descobrir a versão do Oracle" data-count="horizontal" data-via="glufke"></a>
			</div><div style="float:left; width:110px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script type="in/share" data-url="http://glufke.net/2007/08/22/como-descobrir-a-versao-do-oracle/" data-counter="right"></script></div>			
			</div><div style="clear:both"></div><div style="padding-bottom:4px;"></div><p>Existem várias formas de descobrir a versão do Oracle sem olhar a &#8220;telinha inicial&#8221; do SQL*Plus. Neste artigo, debateremos 4 maneiras de se descobrir isso. Algumas são bem conhecidas e outra bem &#8220;raras&#8221; de se ver.<span id="more-6"></span></p>
<p><strong>Usar a V$Version</strong></p>
<pre class="brush: sql;">SQL> select * from v$version;

BANNER
----------------------------------------------------------------
Oracle9i Enterprise Edition Release 9.0.1.4.0 - Production
PL/SQL Release 9.0.1.4.0 - Production
CORE    9.0.1.2.0       Production
TNS for Linux: Version 9.0.1.4.0 - Production
NLSRTL Version 9.0.1.4.0 - Production

5 rows selected.</pre>
<p><strong>SQL que mostra versão</strong></p>
<pre class="brush: sql;">SQL> select trunc( (&#038;_O_RELEASE/100000000)) || '.' ||
  2    trunc( mod((&#038;_O_RELEASE/1000000),100)) || '.' ||
  3    trunc( mod((&#038;_O_RELEASE/10000),100)) || '.' ||
  4    trunc( mod((&#038;_O_RELEASE/100),100))
  5    from dual;

TRUNC((
-------
9.0.1.4

1 row selected.

SQL></pre>
<p><strong>Mais um script interessante</strong></p>
<pre class="brush: sql;">rem -----------------------------------------------------------------------
rem Filename:   ver.sql
rem Purpose:    Show database version with options intalled
rem             (handy for your HELP/ABOUT menu)
rem Date:       12-Nov-1999
rem Author:     Frank Naude (frank@ibi.co.za)
rem -----------------------------------------------------------------------

set head off feed off pages 0 serveroutput on

col banner format a72 wrap

select banner
from   sys.v_$version;

select '   With the '||parameter||' option'
from   sys.v_$option
where  value = 'TRUE';

select '   The '||parameter||' option is not installed'
from   sys.v_$option
where  value <> 'TRUE';

begin
    dbms_output.put_line('Port String: '||dbms_utility.port_string);
end;
/</pre>
<div id="ads_336x280"><script type="text/javascript"><!--
google_ad_client = "pub-8964513116661040";
google_alternate_color = "ffffFF";
google_ad_width = 336;
google_ad_height = 280;
google_ad_format = "336x280_as";
google_ad_type = "text_image";
//2007-09-07: wp_quadrado_gra
google_ad_channel = "0247072216";
google_color_border = "FFFFFF";
google_color_bg = "FFFFff";
google_color_link = "4F82CB";
google_color_text = "000000";
google_color_url = "4F82CB";
//--></script><script type="text/javascript"
  src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<p>Este script gera uma saída como essa:</p>
<pre class="brush: sql;">SQL> @ver
Oracle9i Enterprise Edition Release 9.2.0.5.0 - Production
PL/SQL Release 9.2.0.5.0 - Production
CORE    9.2.0.6.0       Production
TNS for 32-bit Windows: Version 9.2.0.5.0 - Production
NLSRTL Version 9.2.0.5.0 - Production
   With the Partitioning option
   With the Objects option
   With the Advanced replication option
   With the Bit-mapped indexes option
   With the Connection multiplexing option
   With the Connection pooling option
   With the Database queuing option
   With the Incremental backup and recovery option
   With the Instead-of triggers option
   With the Parallel backup and recovery option
   With the Parallel execution option
   With the Parallel load option
   With the Point-in-time tablespace recovery option
   With the Fine-grained access control option
   With the Proxy authentication/authorization option
   With the Change Data Capture option
   With the Plan Stability option
   With the Online Index Build option
   With the Coalesce Index option
   With the Managed Standby option
   With the Materialized view rewrite option
   With the Materialized view warehouse refresh option
   With the Database resource manager option
   With the Spatial option
   With the Visual Information Retrieval option
   With the Export transportable tablespaces option
   With the Transparent Application Failover option
   With the Fast-Start Fault Recovery option
   With the Sample Scan option
   With the Duplexed backups option
   With the Java option
   With the OLAP Window Functions option
   With the Block Media Recovery option
   With the Fine-grained Auditing option
   With the Application Role option
   With the Enterprise User Security option
   With the Oracle Data Guard option
   With the OLAP option
   With the Heap segment compression option
   With the Join index option
   With the Trial Recovery option
   With the Oracle Data Mining option
   With the Online Redefinition option
   With the Streams option
   With the File Mapping option
   The Real Application Clusters option is not installed
   The Oracle Label Security option is not installed
Port String: IBMPC/WIN_NT-8.1.0
SQL></pre>
<p><strong>Usar a DBMS_UTILITY</strong></p>
<pre class="brush: sql;">SQL> DESC DBMS_OUTPUT

PROCEDURE DB_VERSION
 Argument Name                  Type                    In/Out Default?
 ------------------------------ ----------------------- ------ --------
 VERSION                        VARCHAR2                OUT
 COMPATIBILITY                  VARCHAR2                OUT

SQL>
SQL>
SQL> declare
  2  a1 varchar2(1000);
  3  a2 varchar2(1000);
  4  begin
  5    dbms_utility.db_version(a1, a2);
  6    dbms_output.put_line('VERSAO: '||A1||'   COMPATIBILTY: '||A2);
  7  end;
  8  /
VERSAO: 9.2.0.5.0   COMPATIBILTY: 9.2.0.0.0
SQL> </pre>
<p>Comente <a href="http://glufke.net/oracle/viewtopic.php?t=248">aqui</a></p>
]]></content:encoded>
			<wfw:commentRss>http://glufke.net/2007/08/22/como-descobrir-a-versao-do-oracle/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>HELP.SQL dos comandos do SQL*Plus</title>
		<link>http://glufke.net/2007/08/22/helpsql-dos-comandos-do-sqlplus/</link>
		<comments>http://glufke.net/2007/08/22/helpsql-dos-comandos-do-sqlplus/#comments</comments>
		<pubDate>Wed, 22 Aug 2007 23:15:34 +0000</pubDate>
		<dc:creator>glufke</dc:creator>
				<category><![CDATA[SQL]]></category>
		<category><![CDATA[Dicionário de Dados]]></category>
		<category><![CDATA[SQL*Plus]]></category>
		<category><![CDATA[Utilidade]]></category>

		<guid isPermaLink="false">http://glufke.net/2007/08/22/helpsql-dos-comandos-do-sqlplus/</guid>
		<description><![CDATA[
			
			
			
			
			
			
			
						
			O Oracle SQL*Plus possui uma série de comandos que são uma mão na roda! Infelizmente, nem sempre temos o manual completo do SQL*Plus em mãos ou não temos acesso a internet pra pesquisar. É nessa hora que podemos fazer uso de uma tabela do usuário SYSTEM chamada HELP.
Se ela não aparece pra você, então alguém [...]]]></description>
			<content:encoded><![CDATA[<div class="bottomcontainerBox" style="">
			<div style="float:left; width:50px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;">
			<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fglufke.net%2F2007%2F08%2F22%2Fhelpsql-dos-comandos-do-sqlplus%2F&amp;layout=button_count&amp;show_faces=false&amp;width=50&amp;action=like&amp;font=verdana&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" allowTransparency="true" style="border:none; overflow:hidden; width:50px; height:21px;"></iframe></div>
			<div style="float:left; width:60px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;">
			<g:plusone size="medium" href="http://glufke.net/2007/08/22/helpsql-dos-comandos-do-sqlplus/"></g:plusone>
			</div>
			<div style="float:left; width:70px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;">
			<a href="http://twitter.com/share" class="twitter-share-button" data-url="http://glufke.net/2007/08/22/helpsql-dos-comandos-do-sqlplus/"  data-text="HELP.SQL dos comandos do SQL*Plus" data-count="horizontal" data-via="glufke"></a>
			</div><div style="float:left; width:110px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script type="in/share" data-url="http://glufke.net/2007/08/22/helpsql-dos-comandos-do-sqlplus/" data-counter="right"></script></div>			
			</div><div style="clear:both"></div><div style="padding-bottom:4px;"></div><p>O Oracle SQL*Plus possui uma série de comandos que são uma <em>mão na roda</em>! Infelizmente, nem sempre temos o manual completo do SQL*Plus em mãos ou não temos acesso a internet pra pesquisar. É nessa hora que podemos fazer uso de uma tabela do usuário SYSTEM chamada HELP.<span id="more-5"></span></p>
<p>Se ela não aparece pra você, então alguém com privilégio de DBA deve dar um GRANT de select para essa tabela:<br />
<code lang="sql">SQL> grant select to USUARIO;</code></p>
<p>Com base nessa tabela, podemos usar o seguinte script que vai facilitar o serviço:</p>
<p><code lang="sql">SET VER OFF<br />
ACCEPT HELP CHAR PROMPT 'Digite o help (Em branco para mostrar tópicos): ' DEF 'TOPICS'</p>
<p>select info texto<br />
from system.help<br />
where topic=upper('&#038;&#038;HELP')<br />
order by seq<br />
/ </code></p>
<div id="ads_336x280"><script type="text/javascript"><!--
google_ad_client = "pub-8964513116661040";
google_alternate_color = "ffffFF";
google_ad_width = 336;
google_ad_height = 280;
google_ad_format = "336x280_as";
google_ad_type = "text_image";
//2007-09-07: wp_quadrado_gra
google_ad_channel = "0247072216";
google_color_border = "FFFFFF";
google_color_bg = "FFFFff";
google_color_link = "4F82CB";
google_color_text = "000000";
google_color_url = "4F82CB";
//--></script><script type="text/javascript"
  src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<p>Salve o script acima como HELP.SQL e execute da seguinte forma no SQL*Plus:<br />
<code lang="sql">SQL> @help<br />
Digite o help (Em branco para mostrar tÃ³picos): PROMPT</p>
<p>TEXTO<br />
----------------------------------------------------------------</p>
<p> PROMPT<br />
 ------</p>
<p> Sends the specified message or a blank line to the user's<br />
 screen.</p>
<p> PRO[MPT] [text]</p>
<p>SQL> </code></p>
<p>Comente <a href="http://glufke.net/oracle/viewtopic.php?t=10">aqui</a></p>
]]></content:encoded>
			<wfw:commentRss>http://glufke.net/2007/08/22/helpsql-dos-comandos-do-sqlplus/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

