Saudações. !!
Peguei hoje uma situação de uma sequence que estava com mais de 100% de ocupação.
SEQUENCE_OWNER SEQUENCE_NAME MIN_VALUE MAX_VALUE INCREMENT_BY C O LAST_NUMBER PERC
------------------------------ ------------------------------ ---------- ---------- ------------ - - ----------- ----------
OWNER NOME_SEQUENCE 1 999999 1 N N 1000000 100.0001
Todos os sites recomendavam o drop e recriação da mesma, porém como sempre na madruga só podemos contar com pesquisas e Deus, não há como medir o impacto desta ação.
Nem mesmo alterar o incremento máximo da mesma recomendavam
Pesquisando, encontrei o site do ACE Gokhan Atil, foi recomendado que alterasse a sequence para somente começar a incrementar em numeros abaixo do número máximo.
ALTER SEQUENCE OWNER.NOME_SEQUENCE INCREMENT BY -200000;
Isto resolveu completamente o problema sem precisar dropar a sequence.
http://www.gokhanatil.com/2011/01/how-to-set-current-value-of-a-sequence-without-droppingrecreating.html
sexta-feira, 28 de novembro de 2014
segunda-feira, 13 de outubro de 2014
terça-feira, 1 de julho de 2014
Resize do banco - artigo do Burleson Traduzido
Fonte: http://www.dba-oracle.com/art_dbazine_weeg_datafile_resizing_tips.htm
É possível liberar espaço de arquivos de dados, mas apenas para o primeiro bloco de dados.
Isto é feito com o comando "ALTER DATABASE ".
Ao invés de passar pelo tedioso processo de descobrir manualmente o comando cada vez que é usado, faz mais sentido para escrever um script que irá gerar este comando, se necessário.
Alter database name datafile 'file_name' resize size;
Onde name é o nome do banco de dados, file_name é o nome do arquivo e tamanho é o novo tamanho para o resize deste arquivo.
Podemos ver a mudança de tamanho na tabela DBA_DATA_FILES, bem como a partir do servidor.
Em primeiro lugar, puxar o nome do banco de dados:
Select 'alter database '||a.name
From v$database a;
Feito isso, é hora de adicionar os datafiles:
select 'alter database '||a.name||' datafile '''||b.file_name||''''
from v$database a
,dba_data_files b;
Embora este seja mais perto da solução final, não é bastante lá ainda.
A questão permanece: quais arquivos de dados que você quer alterar?
Neste ponto, você pode usar um padrão geralmente aceito, o que permite que os espaços de tabela a ser de 70 por cento para 90 por cento completo.
Se uma tabela está abaixo da marca de 70 por cento, uma maneira de trazer o número para cima é de-alocar uma parte do espaço.
É necessário ver a porcentagem usada.
Quantidade de espaço nos datafiles utilizada:
Select tablespace_name,sum(bytes) bytes_full
From dba_extents
Group by tablespace_name;
mais completa:
Total de espaço disponível nos datafiles:
Select tablespace_name,sum(bytes) bytes_total
From dba_data_files
Group by tablespace_name;
Assim, se somarmos isso com a nossa declaração original, podemos selecionar em pct_used (menos de 70 por cento):
select 'alter database '||a.name||' datafile '''||b.file_name||''''
from v$database a
,dba_data_files b
,(Select tablespace_name,sum(bytes) bytes_full
From dba_extents
Group by tablespace_name) c
,(Select tablespace_name,sum(bytes) bytes_total
From dba_data_files
Group by tablespace_name) d
Where b.tablespace_name = c.tablespace_name
And b.tablespace_name = d.tablespace_name
And bytes_full/bytes_total < .7 ;
De acordo com o comando, a seleção foi feita com base na tabela.
E se você deseja redimensionar baseado em arquivo?
É fundamental lembrar que vários arquivos podem existir em qualquer espaço de tabela.
Além disso, apenas o espaço que é depois do último bloco de dados pode ser de-alocado.
Assim, o próximo passo deve ser o de encontrar o último bloco de dados:
select tablespace_name,file_id,max(block_id) max_data_block_id
from dba_extents
group by tablespace_name,file_id;
Agora que o comando para encontrar o último bloco de dados foi inserido,
é hora de encontrar o espaço livre em cada arquivo acima desse último bloco de dados:
Select a.tablespace_name,a.file_id,b.bytes bytes_free
From (select tablespace_name,file_id,max(block_id) max_data_block_id
from dba_extents
group by tablespace_name,file_id) a
,dba_free_space b
where a.tablespace_name = b.tablespace_name
and a.file_id = b.file_id
and b.block_id > a.max_data_block_id;
Como é possível, então, para combinar comandos para garantir a quantidade correta será redimensionada?
select 'alter database '||a.name||' datafile '''||b.file_name||'''' ||
' resize '||(bytes_total-bytes_free)
from v$database a
,dba_data_files b
,(Select tablespace_name,sum(bytes) bytes_full
From dba_extents
Group by tablespace_name) c
,(Select tablespace_name,sum(bytes) bytes_total
From dba_data_files
Group by tablespace_name) d
,(Select a.tablespace_name,a.file_id,b.bytes bytes_free
From (select tablespace_name,file_id
,max(block_id) max_data_block_id
from dba_extents
group by tablespace_name,file_id) a
,dba_free_space b
where a.tablespace_name = b.tablespace_name
and a.file_id = b.file_id
and b.block_id > a.max_data_block_id) e
Where b.tablespace_name = c.tablespace_name
And b.tablespace_name = d.tablespace_name;
Double check na compactação dos datafiles:
select 'alter database '||a.name||' datafile '''||b.file_name||'''' ||
' resize '||greatest(trunc(bytes_full/.7)
,(bytes_total-bytes_free))
from v$database a
,dba_data_files b
,(Select tablespace_name,sum(bytes) bytes_full
From dba_extents
Group by tablespace_name) c
,(Select tablespace_name,sum(bytes) bytes_total
From dba_data_files
Group by tablespace_name) d
,(Select a.tablespace_name,a.file_id,b.bytes bytes_free
From (select tablespace_name,file_id
,max(block_id) max_data_block_id
from dba_extents
group by tablespace_name,file_id) a
,dba_free_space b
where a.tablespace_name = b.tablespace_name
and a.file_id = b.file_id
and b.block_id > a.max_data_block_id) e
Where b.tablespace_name = c.tablespace_name
And b.tablespace_name = d.tablespace_name
And bytes_full/bytes_total < .7
And b.tablespace_name = e.tablespace_name
And b.file_id = e.file_id ;
Uma última coisa a fazer: Adicione uma instrução para indicar o que está sendo alterado.
Esta query gera os comandos necessários para o resize:
select 'alter database '||a.name||' datafile '''||b.file_name||'''' ||
' resize '||greatest(trunc(bytes_full/.7)
,(bytes_total-bytes_free))||chr(10)||
'--tablespace was '||trunc(bytes_full*100/bytes_total)||
'% full now '||
trunc(bytes_full*100/greatest(trunc(bytes_full/.7)
,(bytes_total-bytes_free)))||'%'
from v$database a
,dba_data_files b
,(Select tablespace_name,sum(bytes) bytes_full
From dba_extents
Group by tablespace_name) c
,(Select tablespace_name,sum(bytes) bytes_total
From dba_data_files
Group by tablespace_name) d
,(Select a.tablespace_name,a.file_id,b.bytes bytes_free
From (select tablespace_name,file_id
,max(block_id) max_data_block_id
from dba_extents
group by tablespace_name,file_id) a
,dba_free_space b
where a.tablespace_name = b.tablespace_name
and a.file_id = b.file_id
and b.block_id > a.max_data_block_id) e
Where b.tablespace_name = c.tablespace_name
And b.tablespace_name = d.tablespace_name
And bytes_full/bytes_total < .7
And b.tablespace_name = e.tablespace_name
And b.file_id = e.file_id ;
exemplo da saída:
'ALTERDATABASE'||A.NAME||'DATAFILE'''||B.FILE_NAME||''''||'RESIZE'||GREATEST(TRU
--------------------------------------------------------------------------------
alter database ORCL datafile '/home/oracle/app/oracle/oradata/orcl/undotbs01.dbf
' resize 31831771
--tablespace was 12% full now 70%
Enfim, este é um script que irá criar o script. Mesmo assim, é importante prestar atenção ao aplicar o script criado.
Por quê? Porque reversão, Sistema e espaços de tabela temporários são muito diferentes criaturas, e cada um não deve necessariamente ser realizada com a regra de 70 por cento.
Da mesma forma, pode haver uma razão muito boa para um espaço de tabela a ser alocado ao longo - como a carga gigante que vai triplicar o volume de noite.
Por fim , cheque os tamanhos das tablespaces novamente:
Select tablespace_name,sum(bytes) bytes_full
From dba_extents
Group by tablespace_name;
Uma palavra de cautela, também: Certifique-se de que as extensões ainda pode ser alocada em cada tabela.
Pode haver espaço livre suficiente, mas pode ser muito fragmentada para ser útil.
Fonte:http://www.dba-oracle.com/art_dbazine_weeg_datafile_resizing_tips.htm
É possível liberar espaço de arquivos de dados, mas apenas para o primeiro bloco de dados.
Isto é feito com o comando "ALTER DATABASE ".
Ao invés de passar pelo tedioso processo de descobrir manualmente o comando cada vez que é usado, faz mais sentido para escrever um script que irá gerar este comando, se necessário.
Alter database name datafile 'file_name' resize size;
Onde name é o nome do banco de dados, file_name é o nome do arquivo e tamanho é o novo tamanho para o resize deste arquivo.
Podemos ver a mudança de tamanho na tabela DBA_DATA_FILES, bem como a partir do servidor.
Em primeiro lugar, puxar o nome do banco de dados:
Select 'alter database '||a.name
From v$database a;
Feito isso, é hora de adicionar os datafiles:
select 'alter database '||a.name||' datafile '''||b.file_name||''''
from v$database a
,dba_data_files b;
Embora este seja mais perto da solução final, não é bastante lá ainda.
A questão permanece: quais arquivos de dados que você quer alterar?
Neste ponto, você pode usar um padrão geralmente aceito, o que permite que os espaços de tabela a ser de 70 por cento para 90 por cento completo.
Se uma tabela está abaixo da marca de 70 por cento, uma maneira de trazer o número para cima é de-alocar uma parte do espaço.
É necessário ver a porcentagem usada.
Quantidade de espaço nos datafiles utilizada:
Select tablespace_name,sum(bytes) bytes_full
From dba_extents
Group by tablespace_name;
mais completa:
SET LINESIZE 200
SET PAGES 150
COL TABLESPACE_NAME FORMAT A15
SELECT A.TABLESPACE_NAME TABLESPACE,
round(A.TAMANHO_MAXIMO,2) TAMANHO_MAXIMO,
round(A.TAMANHO_ATUAL,2) TAMANHO_ATUAL,
A.AUTOEXTENSIBLE EXTEND,
round(B.USADO,2) "USADO(MB)",
round(CASE WHEN A.TAMANHO_MAXIMO<a.TAMANHO_ATUAL THEN A.TAMANHO_ATUAL-B.USADO
ELSE A.TAMANHO_MAXIMO-B.USADO END,2) "LIVRE(MB)",
round(CASE WHEN A.TAMANHO_MAXIMO<a.TAMANHO_ATUAL THEN
(B.USADO/A.TAMANHO_ATUAL)*100 ELSE (B.USADO/A.TAMANHO_MAXIMO)*100 END,2)
"USADO%"
FROM
(SELECT TABLESPACE_NAME,AUTOEXTENSIBLE,
SUM(BYTES/1024/1024) TAMANHO_ATUAL,
SUM(MAXBYTES/1024/1024) TAMANHO_MAXIMO
FROM DBA_DATA_FILES
GROUP BY TABLESPACE_NAME,AUTOEXTENSIBLE) A,
(SELECT TABLESPACE_NAME,
SUM(BYTES/1024/1024) USADO
FROM DBA_SEGMENTS S
GROUP BY TABLESPACE_NAME ) B
WHERE A.TABLESPACE_NAME=B.TABLESPACE_NAME
/
Total de espaço disponível nos datafiles:
Select tablespace_name,sum(bytes) bytes_total
From dba_data_files
Group by tablespace_name;
Assim, se somarmos isso com a nossa declaração original, podemos selecionar em pct_used (menos de 70 por cento):
select 'alter database '||a.name||' datafile '''||b.file_name||''''
from v$database a
,dba_data_files b
,(Select tablespace_name,sum(bytes) bytes_full
From dba_extents
Group by tablespace_name) c
,(Select tablespace_name,sum(bytes) bytes_total
From dba_data_files
Group by tablespace_name) d
Where b.tablespace_name = c.tablespace_name
And b.tablespace_name = d.tablespace_name
And bytes_full/bytes_total < .7 ;
De acordo com o comando, a seleção foi feita com base na tabela.
E se você deseja redimensionar baseado em arquivo?
É fundamental lembrar que vários arquivos podem existir em qualquer espaço de tabela.
Além disso, apenas o espaço que é depois do último bloco de dados pode ser de-alocado.
Assim, o próximo passo deve ser o de encontrar o último bloco de dados:
select tablespace_name,file_id,max(block_id) max_data_block_id
from dba_extents
group by tablespace_name,file_id;
Agora que o comando para encontrar o último bloco de dados foi inserido,
é hora de encontrar o espaço livre em cada arquivo acima desse último bloco de dados:
Select a.tablespace_name,a.file_id,b.bytes bytes_free
From (select tablespace_name,file_id,max(block_id) max_data_block_id
from dba_extents
group by tablespace_name,file_id) a
,dba_free_space b
where a.tablespace_name = b.tablespace_name
and a.file_id = b.file_id
and b.block_id > a.max_data_block_id;
Como é possível, então, para combinar comandos para garantir a quantidade correta será redimensionada?
select 'alter database '||a.name||' datafile '''||b.file_name||'''' ||
' resize '||(bytes_total-bytes_free)
from v$database a
,dba_data_files b
,(Select tablespace_name,sum(bytes) bytes_full
From dba_extents
Group by tablespace_name) c
,(Select tablespace_name,sum(bytes) bytes_total
From dba_data_files
Group by tablespace_name) d
,(Select a.tablespace_name,a.file_id,b.bytes bytes_free
From (select tablespace_name,file_id
,max(block_id) max_data_block_id
from dba_extents
group by tablespace_name,file_id) a
,dba_free_space b
where a.tablespace_name = b.tablespace_name
and a.file_id = b.file_id
and b.block_id > a.max_data_block_id) e
Where b.tablespace_name = c.tablespace_name
And b.tablespace_name = d.tablespace_name;
Double check na compactação dos datafiles:
select 'alter database '||a.name||' datafile '''||b.file_name||'''' ||
' resize '||greatest(trunc(bytes_full/.7)
,(bytes_total-bytes_free))
from v$database a
,dba_data_files b
,(Select tablespace_name,sum(bytes) bytes_full
From dba_extents
Group by tablespace_name) c
,(Select tablespace_name,sum(bytes) bytes_total
From dba_data_files
Group by tablespace_name) d
,(Select a.tablespace_name,a.file_id,b.bytes bytes_free
From (select tablespace_name,file_id
,max(block_id) max_data_block_id
from dba_extents
group by tablespace_name,file_id) a
,dba_free_space b
where a.tablespace_name = b.tablespace_name
and a.file_id = b.file_id
and b.block_id > a.max_data_block_id) e
Where b.tablespace_name = c.tablespace_name
And b.tablespace_name = d.tablespace_name
And bytes_full/bytes_total < .7
And b.tablespace_name = e.tablespace_name
And b.file_id = e.file_id ;
Uma última coisa a fazer: Adicione uma instrução para indicar o que está sendo alterado.
Esta query gera os comandos necessários para o resize:
select 'alter database '||a.name||' datafile '''||b.file_name||'''' ||
' resize '||greatest(trunc(bytes_full/.7)
,(bytes_total-bytes_free))||chr(10)||
'--tablespace was '||trunc(bytes_full*100/bytes_total)||
'% full now '||
trunc(bytes_full*100/greatest(trunc(bytes_full/.7)
,(bytes_total-bytes_free)))||'%'
from v$database a
,dba_data_files b
,(Select tablespace_name,sum(bytes) bytes_full
From dba_extents
Group by tablespace_name) c
,(Select tablespace_name,sum(bytes) bytes_total
From dba_data_files
Group by tablespace_name) d
,(Select a.tablespace_name,a.file_id,b.bytes bytes_free
From (select tablespace_name,file_id
,max(block_id) max_data_block_id
from dba_extents
group by tablespace_name,file_id) a
,dba_free_space b
where a.tablespace_name = b.tablespace_name
and a.file_id = b.file_id
and b.block_id > a.max_data_block_id) e
Where b.tablespace_name = c.tablespace_name
And b.tablespace_name = d.tablespace_name
And bytes_full/bytes_total < .7
And b.tablespace_name = e.tablespace_name
And b.file_id = e.file_id ;
exemplo da saída:
'ALTERDATABASE'||A.NAME||'DATAFILE'''||B.FILE_NAME||''''||'RESIZE'||GREATEST(TRU
--------------------------------------------------------------------------------
alter database ORCL datafile '/home/oracle/app/oracle/oradata/orcl/undotbs01.dbf
' resize 31831771
--tablespace was 12% full now 70%
Enfim, este é um script que irá criar o script. Mesmo assim, é importante prestar atenção ao aplicar o script criado.
Por quê? Porque reversão, Sistema e espaços de tabela temporários são muito diferentes criaturas, e cada um não deve necessariamente ser realizada com a regra de 70 por cento.
Da mesma forma, pode haver uma razão muito boa para um espaço de tabela a ser alocado ao longo - como a carga gigante que vai triplicar o volume de noite.
Por fim , cheque os tamanhos das tablespaces novamente:
Select tablespace_name,sum(bytes) bytes_full
From dba_extents
Group by tablespace_name;
SET LINESIZE 200
SET PAGES 150
COL TABLESPACE_NAME FORMAT A15
SELECT A.TABLESPACE_NAME TABLESPACE,
round(A.TAMANHO_MAXIMO,2) TAMANHO_MAXIMO,
round(A.TAMANHO_ATUAL,2) TAMANHO_ATUAL,
A.AUTOEXTENSIBLE EXTEND,
round(B.USADO,2) "USADO(MB)",
round(CASE WHEN A.TAMANHO_MAXIMO<a.TAMANHO_ATUAL THEN A.TAMANHO_ATUAL-B.USADO
ELSE A.TAMANHO_MAXIMO-B.USADO END,2) "LIVRE(MB)",
round(CASE WHEN A.TAMANHO_MAXIMO<a.TAMANHO_ATUAL THEN
(B.USADO/A.TAMANHO_ATUAL)*100 ELSE (B.USADO/A.TAMANHO_MAXIMO)*100 END,2)
"USADO%"
FROM
(SELECT TABLESPACE_NAME,AUTOEXTENSIBLE,
SUM(BYTES/1024/1024) TAMANHO_ATUAL,
SUM(MAXBYTES/1024/1024) TAMANHO_MAXIMO
FROM DBA_DATA_FILES
GROUP BY TABLESPACE_NAME,AUTOEXTENSIBLE) A,
(SELECT TABLESPACE_NAME,
SUM(BYTES/1024/1024) USADO
FROM DBA_SEGMENTS S
GROUP BY TABLESPACE_NAME ) B
WHERE A.TABLESPACE_NAME=B.TABLESPACE_NAME
/
Uma palavra de cautela, também: Certifique-se de que as extensões ainda pode ser alocada em cada tabela.
Pode haver espaço livre suficiente, mas pode ser muito fragmentada para ser útil.
Fonte:http://www.dba-oracle.com/art_dbazine_weeg_datafile_resizing_tips.htm
sábado, 24 de maio de 2014
quinta-feira, 24 de abril de 2014
Datatypes limits no oracle 11G
http://docs.oracle.com/cd/B28359_01/server.111/b28320/limits001.htm#i287903
Datatype Limits
Datatypes | Limit | Comments |
---|---|---|
BFILE | Maximum size: 4 GB
Maximum size of a file name: 255 characters
Maximum size of a directory name: 30 characters
Maximum number of open BFILEs: see Comments
| The maximum number of BFILEs is limited by the value of theSESSION_MAX_OPEN_FILES initialization parameter, which is itself limited by the maximum number of open files the operating system will allow. |
BLOB | Maximum size: (4 GB - 1) * DB_BLOCK_SIZE initialization parameter (8 TB to 128 TB) | The number of LOB columns per table is limited only by the maximum number of columns per table (that is, 1000Foot 1 ). |
CHAR | Maximum size: 2000 bytes | None |
CHAR VARYING | Maximum size: 4000 bytes | None |
CLOB | Maximum size: (4 GB - 1) * DB_BLOCK_SIZE initialization parameter (8 TB to 128 TB) | The number of LOB columns per table is limited only by the maximum number of columns per table (that is, 1000Footref 1). |
Literals (characters or numbers in SQL or PL/SQL) | Maximum size: 4000 characters | None |
LONG | Maximum size: 2 GB - 1 | Only one LONG column is allowed per table. |
NCHAR | Maximum size: 2000 bytes | None |
NCHAR VARYING | Maximum size: 4000 bytes | None |
NCLOB | Maximum size: (4 GB - 1) * DB_BLOCK_SIZE initialization parameter (8 TB to 128 TB) | The number of LOB columns per table is limited only by the maximum number of columns per table (that is, 1000Footref 1). |
NUMBER | 999...(38 9's) x10125 maximum value
-999...(38 9's) x10125 minimum value
| Can be represented to full 38-digit precision (the mantissa)
Can be represented to full 38-digit precision (the mantissa)
|
Precision | 38 significant digits | None |
RAW | Maximum size: 2000 bytes | None |
VARCHAR | Maximum size: 4000 bytes | None |
VARCHAR2 | Maximum size: 4000 bytes | None |
sábado, 19 de abril de 2014
Usuários - Criação e alteração
http://ss64.com/ora/user_c.html
*************************************************************
-- VERIFICAR QUAIS SÃO OS USUÁRIOS DO SISTEMA
*************************************************************
todos
SELECT USERNAME, created,account_status FROM DBA_USERS;
por usuário
SELECT USERNAME, created, account_status,FROM DBA_USERS WHERE lower (USERNAME)LIKE ‘USER%‘;
*************************************************************
-- CRIAÇÃO
*************************************************************
create USER nome_do_user identified by password;
lockar, deslocar
alter user nome_do_user ACCOUNT UNLOCK /LOCK;
ALTER user username password EXPIRE -> forçar alteração de senha
OPÇÕES DE CRIAÇÃO
Syntax:
CREATE USER username
IDENTIFIED {BY password | EXTERNALLY | GLOBALLY AS 'external_name'}
options;
options:
DEFAULT TABLESPACE tablespace
TEMPORARY TABLESPACE tablespace
QUOTA int {K | M} ON tablespace
QUOTA UNLIMITED ON tablespace
PROFILE profile_name
PASSWORD EXPIRE
ACCOUNT {LOCK|UNLOCK}
*************************************************************
ATIVAÇÃO
*************************************************************
ALTER user username account lock
ALTER user username account unlock
*************************************************************
---VERIFICAR COTAS E TABLESPACES:
*************************************************************
set linesize 128
SELECT USERNAME, DEFAULT_TABLESPACE,TEMPORARY_TABLESPACE FROM DBA_USERS WHERE lower(USERNAME) LIKE 'USER%'
SELECT USERNAME, DEFAULT_TABLESPACE,TEMPORARY_TABLESPACE FROM DBA_USERS WHERE lower(USERNAME) LIKE 'scott%';
ALTERAR TABLESPACE
ALTER USER USERNAME TEMPORARY |DEFAULT TABLESPACE tablespace_name
*************************************************************
--COTAS
*************************************************************
ALTERAR A COTA
ALTER USER nome_do_user quota tamanho_da_cota on nome_tablespace
alter user scott quota 10m on users;
alter user scott quota unlimited on example;
CHECAR COTA
select tablespace_name,bytes,max_bytes from dba_ts_quotas where username='nome_do_user';
select tablespace_name,bytes,max_bytes from dba_ts_quotas where username='GTORRES';
TABLESPACES PADRÃO DO BANCO
SELECT property_name , property_value from database_properties WHERE property_name like'%TABLESPACE';
*************************************************************
--- AUTENTICAÇÃO
*************************************************************
connect username/password@db_alias as privilegio
conn sys/oracle@orcl as sysdba
CHECAR OS PRIVILEGIOS SYSDBA E SYSOPER checar a view V$PWFILE_USERS
select *from V$PWFILE_USERS;
CHECAR AUTENTICAÇÃO PELO SO
select value from v$parameter where name='os_authent_prefix';
CRIANDO um user com autenticação pelo SO -> inserir o valor padrão ops$ antes do nome criado e após o parametro identified externally
NO Unix, qualquer usuário criado dessa maneira será capaz de emitir o comando sqlplus /
create user ops$nome_user indentified externally;
no windows:
create user "OPS$DOMINIO_DA_MAQUINA\USER_DO_SO" identified externally;
*************************************************************
-- GRANTS
*************************************************************
grant privilegio to user
revoke privilegio from user
ex:
GRANT select any table to username
GRANT CREATE SESSION to username
GRANT ROLE_NAME TO USER_NAME with admin option
GRANT privilegio on schema.user object to username
GRANT privilegio on schema.user object to username with GRANT option
GRANT privilegio on schema.user object to username with ADMIN option
grant all on schema.user to ROLE_NAME
checando privilégios
select *from dba_role_privs where grantee ='JON';
DROPANDO
DROP USER SchemaOwner CASCADE;
CREATE USER MySchemaOwner IDENTIFIED BY ChangeThis
DEFAULT TABLESPACE data
TEMPORARY TABLESPACE temp
QUOTA UNLIMITED ON data;
CREATE ROLE conn;
GRANT CREATE session, CREATE table, CREATE view,
CREATE procedure,CREATE synonym,
ALTER table, ALTER view, ALTER procedure,ALTER synonym,
DROP table, DROP view, DROP procedure,DROP synonym,
TO conn;
GRANT conn TO SchemaOwner;
*************************************************************
-- VERIFICAR QUAIS SÃO OS USUÁRIOS DO SISTEMA
*************************************************************
todos
SELECT USERNAME, created,account_status FROM DBA_USERS;
por usuário
SELECT USERNAME, created, account_status,FROM DBA_USERS WHERE lower (USERNAME)LIKE ‘USER%‘;
*************************************************************
-- CRIAÇÃO
*************************************************************
create USER nome_do_user identified by password;
lockar, deslocar
alter user nome_do_user ACCOUNT UNLOCK /LOCK;
ALTER user username password EXPIRE -> forçar alteração de senha
OPÇÕES DE CRIAÇÃO
Syntax:
CREATE USER username
IDENTIFIED {BY password | EXTERNALLY | GLOBALLY AS 'external_name'}
options;
options:
DEFAULT TABLESPACE tablespace
TEMPORARY TABLESPACE tablespace
QUOTA int {K | M} ON tablespace
QUOTA UNLIMITED ON tablespace
PROFILE profile_name
PASSWORD EXPIRE
ACCOUNT {LOCK|UNLOCK}
*************************************************************
ATIVAÇÃO
*************************************************************
ALTER user username account lock
ALTER user username account unlock
*************************************************************
---VERIFICAR COTAS E TABLESPACES:
*************************************************************
set linesize 128
SELECT USERNAME, DEFAULT_TABLESPACE,TEMPORARY_TABLESPACE FROM DBA_USERS WHERE lower(USERNAME) LIKE 'USER%'
SELECT USERNAME, DEFAULT_TABLESPACE,TEMPORARY_TABLESPACE FROM DBA_USERS WHERE lower(USERNAME) LIKE 'scott%';
ALTERAR TABLESPACE
ALTER USER USERNAME TEMPORARY |DEFAULT TABLESPACE tablespace_name
*************************************************************
--COTAS
*************************************************************
ALTERAR A COTA
ALTER USER nome_do_user quota tamanho_da_cota on nome_tablespace
alter user scott quota 10m on users;
alter user scott quota unlimited on example;
CHECAR COTA
select tablespace_name,bytes,max_bytes from dba_ts_quotas where username='nome_do_user';
select tablespace_name,bytes,max_bytes from dba_ts_quotas where username='GTORRES';
TABLESPACES PADRÃO DO BANCO
SELECT property_name , property_value from database_properties WHERE property_name like'%TABLESPACE';
*************************************************************
--- AUTENTICAÇÃO
*************************************************************
connect username/password@db_alias as privilegio
conn sys/oracle@orcl as sysdba
CHECAR OS PRIVILEGIOS SYSDBA E SYSOPER checar a view V$PWFILE_USERS
select *from V$PWFILE_USERS;
CHECAR AUTENTICAÇÃO PELO SO
select value from v$parameter where name='os_authent_prefix';
CRIANDO um user com autenticação pelo SO -> inserir o valor padrão ops$ antes do nome criado e após o parametro identified externally
NO Unix, qualquer usuário criado dessa maneira será capaz de emitir o comando sqlplus /
create user ops$nome_user indentified externally;
no windows:
create user "OPS$DOMINIO_DA_MAQUINA\USER_DO_SO" identified externally;
*************************************************************
-- GRANTS
*************************************************************
grant privilegio to user
revoke privilegio from user
ex:
GRANT select any table to username
GRANT CREATE SESSION to username
GRANT ROLE_NAME TO USER_NAME with admin option
GRANT privilegio on schema.user object to username
GRANT privilegio on schema.user object to username with GRANT option
GRANT privilegio on schema.user object to username with ADMIN option
grant all on schema.user to ROLE_NAME
checando privilégios
select *from dba_role_privs where grantee ='JON';
DROPANDO
DROP USER SchemaOwner CASCADE;
CREATE USER MySchemaOwner IDENTIFIED BY ChangeThis
DEFAULT TABLESPACE data
TEMPORARY TABLESPACE temp
QUOTA UNLIMITED ON data;
CREATE ROLE conn;
GRANT CREATE session, CREATE table, CREATE view,
CREATE procedure,CREATE synonym,
ALTER table, ALTER view, ALTER procedure,ALTER synonym,
DROP table, DROP view, DROP procedure,DROP synonym,
TO conn;
GRANT conn TO SchemaOwner;
quarta-feira, 9 de abril de 2014
TABLESPACES
criação - pag 261 - 265
sintaxes:
http://ss64.com/ora/tablespace_c.html
http://docs.oracle.com/cd/B28359_01/server.111/b28286/statements_7003.htm#SQLRF01403
Sintaxe criação
create TABLESPACE nome_tablespace
DATAFILE 'CAMINHO_DATAFILE\NOME_DATAFILE_1.DBF' size 1G (m|g|t) --EXEMPLO 'C:\ORADATA\GLTABS\_01.DBF'
'CAMINHO_DATAFILE\NOME_DATAFILE_2.DBF' size 1G
extent management local uniform size 5120k;
----------------------
COM FLASHBACK
----------------------
CREATE TABLESPACE APPL_DATA
DATAFILE ‘/disk3/oradata/DB01/appl_data01.dbf’
SIZE 100M
DEFAULT STORAGE COMPRESS
BLOCKSIZE 16K
LOGGING
ONLINE
FORCE LOGGING
FLASHBACK ON
EXTENT MANAGEMENT LOCAL
SEGMENT SPACE MANAGEMENT AUTO;
CREATE TABLESPACE ts_myapp DATAFILE
'/data/ts_myapp01.dbf' SIZE 200M,
'/data/ts_myapp02.dbf' SIZE 500M
logging
autoextend off
extent management local;
----------------------
UNDO TABLESPACE
----------------------
-> CREATE UNDO TABLESPACE nome_tablespace_undo01
datafile '/data/ts_undo01.dbf' SIZE 50000M REUSE
autoextend on
RETENTION NOGUARANTEE | RETENTION GUARANTEE;
-> CREATE UNDO TABLESPACE ts_undo01 DATAFILE
'/data/ts_undo01.dbf' SIZE 50000M REUSE
autoextend on
RETENTION NOGUARANTEE;
------------------------------------------------------------
CRIANDO Bigfile and Smallfile Tablespaces
CREATE BIGFILE TABLESPACE PO_ARCHIVE
DATAFILE ‘/u02/oradata/11GR11/po_archive.dbf’ size 25G;
CREATE SMALLFILE TABLESPACE PO_DETAILS
DATAFILE ‘/u02/oradata/11GR11/po_details.dbf’ size 2G;
----------------------------------------------------------------------------------
TRABALHANDO COM OMF
ALTER SYSTEM SET
db_create_file_dest = ‘/u02/oradata/’ SCOPE=BOTH;
When creating a tablespace using the OMF feature, you simply omit the filename:
CREATE TABLESPACE hr_data;
exemplo:
alter system set DB_CREATE_FILE_DEST ='/home/db11g/oradata';
ou alterar nos parametros:
DB_CREATE_FILE_DEST
DB_CREATE_ONLINE_LOG_DEST_1
DB_CREATE_ONLINE_LOG_DEST_2
DB_CREATE_ONLINE_LOG_DEST_3
DB_CREATE_ONLINE_LOG_DEST_4
DB_CREATE_ONLINE_LOG_DEST_5
DB_RECOVERY_FILE_DEST
********************************************************************************************
ALTERAÇÃO - Sequencia
1 -INVESTIGAR O CAMINHO - Usar as views
todas - V$TABLESPACE
views - temp -> v$tempfile e dba_temp_files
datafiles ->v$datafile e dba_data_files , DBA_SEGMENTS
DBA_DATA_FILES
DBA_TABLESPACES
USER_TABLESPACES
DBA_TEMP_FILES
DBA_TS_QUOTAS
USER_TS_QUOTAS
Steps
1 - > criar a tablespace
create smallfile tablespace newts
datafile 'C:\oracle\app\oradata\orcl\newsts01.dbf'
size 100m autoextend on next 10m maxsize 200m
logging
extent management local
segment space management auto
default nocompress;
2 - -> renomear a tablespace
ALTER TABLESPACE tablespaceOLDname RENAME TO tablespaceNEWname;
ALTER TABLESPACE newts RENAME TO newts02;
3 - -> colocar a nova tablespace offline
ALTER TABLESPACE newts02 OFFLINE;
4 - -> renomear os datafiles no SO
host rename CAMINHO_OLD_DATAFILE\NOME_OLD_DATAFILE_.DBF NOME_NEW_DATAFILE.DBF
host rename C:\oracle\app\oradata\orcl\newsts01.dbf newsts02.dbf;
5 - -> ALTERAR no banco o antigo datafile
ALTER DATABASE rename file 'C:\oracle\app\oradata\orcl\newsts01.dbf'
TO 'C:\oracle\app\oradata\orcl\newsts02.dbf';
6 - -> Colocar a tablespace online
ALTER TABLESPACE tablespaceNEWname ONLINE;
ALTER TABLESPACE newts02 ONLINE;
7 - Checando
obs: @dba_tablespaces
ou usar a query
select substr(a.tablespace_name,1,20) "Tablespaces",
(b.BYTES/1048576) as "TotalMB",
(b.BYTES/1048576)-(c.BYTES/1048576) as "UsedMB",
(c.BYTES/1048576) as "FreeMB"
from dba_tablespaces a,
(select tablespace_name,sum(bytes) as "BYTES"
from dba_data_files
group by tablespace_name ) b,
(select tablespace_name,sum(bytes) as "BYTES"
from dba_free_space
group by tablespace_name) c
where
a.tablespace_name = b.tablespace_name(+)
and b.tablespace_name = c.tablespace_name(+)
order by a.tablespace_name;
Dropando
drop tablespace newts02 including contents and datafiles;
****************************************************************************
MARCAR COMO LEITURA- GRAVAÇÃO OU SOMENTE LEITURA
para somente LEITURA -> ALTER TABLESPACE NOME_TABLESPACE read only
para ler e gravar -> ALTER TABLESPACE NOME_TABLESPACE read write
PARA REDIMENSIONAR O DATAFILE
sintaxe - ALTER DATABASE TIPO_DO_DATAFILE NOME_DO_DATAFILE RESIZE M|g|t
-> ALTER DATABASE DATAFILE 'C:\oracle\app\oradata\orcl\newsts02.dbf' resize 10m;
ALTER DATABASE DATAFILE 'C:\oracle\app\oradata\orcl\newsts02.dbf' resize 10m;
autoextend on next 100m maxsize 4G ; ---- Não esquecer de botar o limite máximo, neste exemplo é 4G
---------------------------------------------------------------------------------
PARA ADICIONAR DATAFILE
ALTER TABLESPACE NOME_TABLESPACE
add datafile 'caminho_e_nome.dbf' size M|g|t ;
exemplo ->
ALTER TABLESPACE gl_large_tabs
add datafile 'C:\oracle\app\oradata\orcl\newsts02.dbf' size 2g ;
no Linux
alter tablespace nome_tablespace add datafile
'/dev/vx/rdsk/oracledg/db_name_data02.dbf' size 6001m
---------------------------------------------------------------------------------
GERENCIANDO ESPAÇOS
OBS: PARA AUMENTAR TABLESPACE - SE ADICIONA DATAFILES - ADD DATAFILE
exemplo ->
ALTER TABLESPACE gl_large_tabs
add datafile 'C:\oracle\app\oradata\orcl\newsts02.dbf' size 2g ;
PARA AUMENTAR SEGMENTOS ( DENTRO DA TABLESPACE ) - SE ALOCA EXTENSÕES - allocate extent
-- > alter table newtabs allocate extent;
E DENTRO DOS SEGMENTOS, são aumentadas as linhas
-----------------------------------------------------------------------
CONVERTENDO GERENCIAMENTO POR DICIONÁRIO PARA LOCAL (O IDEAL):
OBS: para criar uma com gerenciamento manual (não e´o ideal - pag 275)
-> create tablespace NOME_TABLESPACE SEGMENT SPACE MANAGEMENT LOCAL
1 - verificar pelas querys se há tablespace com gerenciamento local:
select tablespace_name, extent management from dba_tablespaces;
select tablespace_name, segment_space_management from dba_tablespaces;
Checar pelo nome da tablespace:
-> select segment_space_management from dba_tablespaces where tablespace_name='NOME_TABLESPACE'
2 - para converter para auto:
execute dbms_space_admin.tablespace_migrate_to local('tablespace_name')
Para alterar o TRESHOLD NO EM: tablespace / edit tablespace /TRESHOLD
**********************************************************************************************
PARA MOVER SEGMENTOS:
ALTER tipo_de segmento nome_do_segmento MOVE TABLESPACE nome_TABLESPACE_ANTIGA
tipo_de segmento nome_do_segmento MOVE nome_TABLESPACE_NOVA;
->
ALTER table mantab MOVE TABLESPACE autosalter table mantab MOVE TABLESPACE autosegs;
Se tiver indices, fazer o rebuild
alter index mantabi rebuild ONLINE TABLESPACE autosegs;s;
CONFIRMAR SE ESTÃO NA TABLESPACE correta
-> select tablespace_name from DBA_SEGMENTS WHERE SEGMENT_NAME LIKE 'MANTAB%'
-----------------------------------------------------------------------------------------------------------
Aumento de Tablespace
select SUM(bytes/1024/1024/1024) from dba_free_space where tablespace_name = 'APPS_TS_TX_DATA';
---> verificar tamanho de uma tablespace
select file_name, bytes/1024/1024/1024 from dba_data_files where tablespace_name = 'USERS' order by file_name;
---> verificar qual o ultimo dbf para adicionar
Informações das tablespaces - Oracle
select substr(a.tablespace_name,1,20) "Tablespaces",
(b.BYTES/1048576) as "TotalMB",
(b.BYTES/1048576)-(c.BYTES/1048576) as "UsedMB",
(c.BYTES/1048576) as "FreeMB"
from dba_tablespaces a,
(select tablespace_name,sum(bytes) as "BYTES"
from dba_data_files
group by tablespace_name ) b,
(select tablespace_name,sum(bytes) as "BYTES"
from dba_free_space
group by tablespace_name) c
where
a.tablespace_name = b.tablespace_name(+)
and b.tablespace_name = c.tablespace_name(+)
order by a.tablespace_name;
Ver tablespaces com menos de 20% livre
COL tbs FORMAT a25
COL total(mb) FORMAT 999,990.00
COL livre(mb) FORMAT 999,990.00
COL livre(%) FORMAT 990.00
select instance_name,host_name,to_char(sysdate,'dd/mm/yy hh24:mi') from v$instance;
SELECT DISTINCT d.tablespace_name "NOME DA TABLESPACE",t.total "TOTAL(MB)", NVL(f.livre,0) "LIVRE(MB)", (NVL(f.livre,0)*100/t.total) "LIVRE(%)"
FROM dba_data_files d,
(SELECT tablespace_name ,sum(bytes)/1024/1024 total FROM dba_data_files GROUP BY tablespace_name) t,
(SELECT tablespace_name ,sum(bytes)/1024/1024 livre FROM dba_free_space GROUP BY tablespace_name) f
WHERE d.tablespace_name =t.tablespace_name
AND d.tablespace_name = f.tablespace_name(+)
AND (NVL(f.livre,0)*100/t.total) <= 20
ORDER BY 4 DESC;
Listar os datafiles das tablespaces
COL tablespace_name FORMAT a15
COL file_name FORMAT a45
COL size_mb FORMAT 999,990.00
COL autoextensible FORMAT a5
select df.tablespace_name, df.file_name, df.bytes/1024/1024 size_mb, df.status, df.autoextensible
from dba_data_files df
where df.tablespace_name='&tablespace_name';
Adicionar espaço na tablespace
Resize: alter database datafile '/oracle/oradata/nome_datafile.dbf' resize 8192 m
Create: alter tablespace nome_tablespace add datafile '/dev/vx/rdsk/oracledg/db_name_data02.dbf' size 6001m
Script para adição de um novo data file em dada tablespace.
SQL> alter tablespace nome_tablespace
add datafile '/oracle/SID/sapdata2/btabi_10/btabi.data10' size 1024064K
autoextend on
next 1024064K
maxsize 16777280K;
#tablespace de undo#
CREATE UNDO TABLESPACE UNDOTBS DATAFILE
'c:\oracle9i\treino9i\UNDOTBS.dbf' SIZE 350M
#Criar tablespace temp#
CREATE TEMPORARY TABLESPACE teste DATAFILE
'/proj/ebsdsgev/oradata/teste.dbf' SIZE 1024M
DEFAULT STORAGE (INITIAL 1024 K NEXT 1024 K
MAXEXTENTS unlimited PCTINCREASE 0);
#Criar tablespace TMP#
CREATE TEMPORARY TABLESPACE TEMP3
TEMPFILE '/proj/ebsdsgev/oradata/temp03.dbf'
SIZE 1024M AUTOEXTEND ON;
#apagar tablespace#
DROP TABLESPACE temp2 INCLUDING CONTENTS AND DATAFILES;
#Ver qual tablespace esta como temp#
select PROPERTY_NAME, PROPERTY_VALUE from database_properties where PROPERTY_NAME like '%TABLESPACE%';
Obrigado ao meu amigo Bruno Pelegrini pelas dicas
sintaxes:
http://ss64.com/ora/tablespace_c.html
http://docs.oracle.com/cd/B28359_01/server.111/b28286/statements_7003.htm#SQLRF01403
Sintaxe criação
create TABLESPACE nome_tablespace
DATAFILE 'CAMINHO_DATAFILE\NOME_DATAFILE_1.DBF' size 1G (m|g|t) --EXEMPLO 'C:\ORADATA\GLTABS\_01.DBF'
'CAMINHO_DATAFILE\NOME_DATAFILE_2.DBF' size 1G
extent management local uniform size 5120k;
----------------------
COM FLASHBACK
----------------------
CREATE TABLESPACE APPL_DATA
DATAFILE ‘/disk3/oradata/DB01/appl_data01.dbf’
SIZE 100M
DEFAULT STORAGE COMPRESS
BLOCKSIZE 16K
LOGGING
ONLINE
FORCE LOGGING
FLASHBACK ON
EXTENT MANAGEMENT LOCAL
SEGMENT SPACE MANAGEMENT AUTO;
CREATE TABLESPACE ts_myapp DATAFILE
'/data/ts_myapp01.dbf' SIZE 200M,
'/data/ts_myapp02.dbf' SIZE 500M
logging
autoextend off
extent management local;
----------------------
UNDO TABLESPACE
----------------------
-> CREATE UNDO TABLESPACE nome_tablespace_undo01
datafile '/data/ts_undo01.dbf' SIZE 50000M REUSE
autoextend on
RETENTION NOGUARANTEE | RETENTION GUARANTEE;
-> CREATE UNDO TABLESPACE ts_undo01 DATAFILE
'/data/ts_undo01.dbf' SIZE 50000M REUSE
autoextend on
RETENTION NOGUARANTEE;
------------------------------------------------------------
CRIANDO Bigfile and Smallfile Tablespaces
CREATE BIGFILE TABLESPACE PO_ARCHIVE
DATAFILE ‘/u02/oradata/11GR11/po_archive.dbf’ size 25G;
CREATE SMALLFILE TABLESPACE PO_DETAILS
DATAFILE ‘/u02/oradata/11GR11/po_details.dbf’ size 2G;
----------------------------------------------------------------------------------
TRABALHANDO COM OMF
ALTER SYSTEM SET
db_create_file_dest = ‘/u02/oradata/’ SCOPE=BOTH;
When creating a tablespace using the OMF feature, you simply omit the filename:
CREATE TABLESPACE hr_data;
exemplo:
alter system set DB_CREATE_FILE_DEST ='/home/db11g/oradata';
ou alterar nos parametros:
DB_CREATE_FILE_DEST
DB_CREATE_ONLINE_LOG_DEST_1
DB_CREATE_ONLINE_LOG_DEST_2
DB_CREATE_ONLINE_LOG_DEST_3
DB_CREATE_ONLINE_LOG_DEST_4
DB_CREATE_ONLINE_LOG_DEST_5
DB_RECOVERY_FILE_DEST
********************************************************************************************
ALTERAÇÃO - Sequencia
1 -INVESTIGAR O CAMINHO - Usar as views
todas - V$TABLESPACE
views - temp -> v$tempfile e dba_temp_files
datafiles ->v$datafile e dba_data_files , DBA_SEGMENTS
DBA_DATA_FILES
DBA_TABLESPACES
USER_TABLESPACES
DBA_TEMP_FILES
DBA_TS_QUOTAS
USER_TS_QUOTAS
Steps
1 - > criar a tablespace
create smallfile tablespace newts
datafile 'C:\oracle\app\oradata\orcl\newsts01.dbf'
size 100m autoextend on next 10m maxsize 200m
logging
extent management local
segment space management auto
default nocompress;
2 - -> renomear a tablespace
ALTER TABLESPACE tablespaceOLDname RENAME TO tablespaceNEWname;
ALTER TABLESPACE newts RENAME TO newts02;
3 - -> colocar a nova tablespace offline
ALTER TABLESPACE newts02 OFFLINE;
4 - -> renomear os datafiles no SO
host rename CAMINHO_OLD_DATAFILE\NOME_OLD_DATAFILE_.DBF NOME_NEW_DATAFILE.DBF
host rename C:\oracle\app\oradata\orcl\newsts01.dbf newsts02.dbf;
5 - -> ALTERAR no banco o antigo datafile
ALTER DATABASE rename file 'C:\oracle\app\oradata\orcl\newsts01.dbf'
TO 'C:\oracle\app\oradata\orcl\newsts02.dbf';
6 - -> Colocar a tablespace online
ALTER TABLESPACE tablespaceNEWname ONLINE;
ALTER TABLESPACE newts02 ONLINE;
7 - Checando
obs: @dba_tablespaces
ou usar a query
select substr(a.tablespace_name,1,20) "Tablespaces",
(b.BYTES/1048576) as "TotalMB",
(b.BYTES/1048576)-(c.BYTES/1048576) as "UsedMB",
(c.BYTES/1048576) as "FreeMB"
from dba_tablespaces a,
(select tablespace_name,sum(bytes) as "BYTES"
from dba_data_files
group by tablespace_name ) b,
(select tablespace_name,sum(bytes) as "BYTES"
from dba_free_space
group by tablespace_name) c
where
a.tablespace_name = b.tablespace_name(+)
and b.tablespace_name = c.tablespace_name(+)
order by a.tablespace_name;
Dropando
drop tablespace newts02 including contents and datafiles;
****************************************************************************
MARCAR COMO LEITURA- GRAVAÇÃO OU SOMENTE LEITURA
para somente LEITURA -> ALTER TABLESPACE NOME_TABLESPACE read only
para ler e gravar -> ALTER TABLESPACE NOME_TABLESPACE read write
PARA REDIMENSIONAR O DATAFILE
sintaxe - ALTER DATABASE TIPO_DO_DATAFILE NOME_DO_DATAFILE RESIZE M|g|t
-> ALTER DATABASE DATAFILE 'C:\oracle\app\oradata\orcl\newsts02.dbf' resize 10m;
ALTER DATABASE DATAFILE 'C:\oracle\app\oradata\orcl\newsts02.dbf' resize 10m;
autoextend on next 100m maxsize 4G ; ---- Não esquecer de botar o limite máximo, neste exemplo é 4G
---------------------------------------------------------------------------------
PARA ADICIONAR DATAFILE
ALTER TABLESPACE NOME_TABLESPACE
add datafile 'caminho_e_nome.dbf' size M|g|t ;
exemplo ->
ALTER TABLESPACE gl_large_tabs
add datafile 'C:\oracle\app\oradata\orcl\newsts02.dbf' size 2g ;
no Linux
alter tablespace nome_tablespace add datafile
'/dev/vx/rdsk/oracledg/db_name_data02.dbf' size 6001m
---------------------------------------------------------------------------------
GERENCIANDO ESPAÇOS
OBS: PARA AUMENTAR TABLESPACE - SE ADICIONA DATAFILES - ADD DATAFILE
exemplo ->
ALTER TABLESPACE gl_large_tabs
add datafile 'C:\oracle\app\oradata\orcl\newsts02.dbf' size 2g ;
PARA AUMENTAR SEGMENTOS ( DENTRO DA TABLESPACE ) - SE ALOCA EXTENSÕES - allocate extent
-- > alter table newtabs allocate extent;
E DENTRO DOS SEGMENTOS, são aumentadas as linhas
-----------------------------------------------------------------------
CONVERTENDO GERENCIAMENTO POR DICIONÁRIO PARA LOCAL (O IDEAL):
OBS: para criar uma com gerenciamento manual (não e´o ideal - pag 275)
-> create tablespace NOME_TABLESPACE SEGMENT SPACE MANAGEMENT LOCAL
1 - verificar pelas querys se há tablespace com gerenciamento local:
select tablespace_name, extent management from dba_tablespaces;
select tablespace_name, segment_space_management from dba_tablespaces;
Checar pelo nome da tablespace:
-> select segment_space_management from dba_tablespaces where tablespace_name='NOME_TABLESPACE'
2 - para converter para auto:
execute dbms_space_admin.tablespace_migrate_to local('tablespace_name')
Para alterar o TRESHOLD NO EM: tablespace / edit tablespace /TRESHOLD
**********************************************************************************************
PARA MOVER SEGMENTOS:
ALTER tipo_de segmento nome_do_segmento MOVE TABLESPACE nome_TABLESPACE_ANTIGA
tipo_de segmento nome_do_segmento MOVE nome_TABLESPACE_NOVA;
->
ALTER table mantab MOVE TABLESPACE autosalter table mantab MOVE TABLESPACE autosegs;
Se tiver indices, fazer o rebuild
alter index mantabi rebuild ONLINE TABLESPACE autosegs;s;
CONFIRMAR SE ESTÃO NA TABLESPACE correta
-> select tablespace_name from DBA_SEGMENTS WHERE SEGMENT_NAME LIKE 'MANTAB%'
-----------------------------------------------------------------------------------------------------------
Querys importantes:
Aumento de Tablespace
select SUM(bytes/1024/1024/1024) from dba_free_space where tablespace_name = 'APPS_TS_TX_DATA';
---> verificar tamanho de uma tablespace
select file_name, bytes/1024/1024/1024 from dba_data_files where tablespace_name = 'USERS' order by file_name;
---> verificar qual o ultimo dbf para adicionar
Informações das tablespaces - Oracle
select substr(a.tablespace_name,1,20) "Tablespaces",
(b.BYTES/1048576) as "TotalMB",
(b.BYTES/1048576)-(c.BYTES/1048576) as "UsedMB",
(c.BYTES/1048576) as "FreeMB"
from dba_tablespaces a,
(select tablespace_name,sum(bytes) as "BYTES"
from dba_data_files
group by tablespace_name ) b,
(select tablespace_name,sum(bytes) as "BYTES"
from dba_free_space
group by tablespace_name) c
where
a.tablespace_name = b.tablespace_name(+)
and b.tablespace_name = c.tablespace_name(+)
order by a.tablespace_name;
Ver tablespaces com menos de 20% livre
COL tbs FORMAT a25
COL total(mb) FORMAT 999,990.00
COL livre(mb) FORMAT 999,990.00
COL livre(%) FORMAT 990.00
select instance_name,host_name,to_char(sysdate,'dd/mm/yy hh24:mi') from v$instance;
SELECT DISTINCT d.tablespace_name "NOME DA TABLESPACE",t.total "TOTAL(MB)", NVL(f.livre,0) "LIVRE(MB)", (NVL(f.livre,0)*100/t.total) "LIVRE(%)"
FROM dba_data_files d,
(SELECT tablespace_name ,sum(bytes)/1024/1024 total FROM dba_data_files GROUP BY tablespace_name) t,
(SELECT tablespace_name ,sum(bytes)/1024/1024 livre FROM dba_free_space GROUP BY tablespace_name) f
WHERE d.tablespace_name =t.tablespace_name
AND d.tablespace_name = f.tablespace_name(+)
AND (NVL(f.livre,0)*100/t.total) <= 20
ORDER BY 4 DESC;
Listar os datafiles das tablespaces
COL tablespace_name FORMAT a15
COL file_name FORMAT a45
COL size_mb FORMAT 999,990.00
COL autoextensible FORMAT a5
select df.tablespace_name, df.file_name, df.bytes/1024/1024 size_mb, df.status, df.autoextensible
from dba_data_files df
where df.tablespace_name='&tablespace_name';
Adicionar espaço na tablespace
Resize: alter database datafile '/oracle/oradata/nome_datafile.dbf' resize 8192 m
Create: alter tablespace nome_tablespace add datafile '/dev/vx/rdsk/oracledg/db_name_data02.dbf' size 6001m
Script para adição de um novo data file em dada tablespace.
SQL> alter tablespace nome_tablespace
add datafile '/oracle/SID/sapdata2/btabi_10/btabi.data10' size 1024064K
autoextend on
next 1024064K
maxsize 16777280K;
#tablespace de undo#
CREATE UNDO TABLESPACE UNDOTBS DATAFILE
'c:\oracle9i\treino9i\UNDOTBS.dbf' SIZE 350M
#Criar tablespace temp#
CREATE TEMPORARY TABLESPACE teste DATAFILE
'/proj/ebsdsgev/oradata/teste.dbf' SIZE 1024M
DEFAULT STORAGE (INITIAL 1024 K NEXT 1024 K
MAXEXTENTS unlimited PCTINCREASE 0);
#Criar tablespace TMP#
CREATE TEMPORARY TABLESPACE TEMP3
TEMPFILE '/proj/ebsdsgev/oradata/temp03.dbf'
SIZE 1024M AUTOEXTEND ON;
#apagar tablespace#
DROP TABLESPACE temp2 INCLUDING CONTENTS AND DATAFILES;
#Ver qual tablespace esta como temp#
select PROPERTY_NAME, PROPERTY_VALUE from database_properties where PROPERTY_NAME like '%TABLESPACE%';
Obrigado ao meu amigo Bruno Pelegrini pelas dicas
segunda-feira, 24 de março de 2014
Eventos de espera no ORACLE
Evento de Espera | Descrição - quando o processo..... |
enqueue | está esperando pelo liberamento de algum recurso |
library cache pin | quer examinar algum objeto e certificar que ninguém conseguirá alterá-lo neste tempo. |
library cache load Lock | está
esperando pela oportunidade de carregar um objeto ou parte de um objeto na biblioteca de cache. |
latch free | está
esperando por um latch (termo usado quando um grande número de processos estão competindo pelo acesso a algum objeto interno) |
buffer busy waits | quer
acesso a um bloco de dados que não está na memória, mas que outro já requisitou uma E/S para trazê-lo. |
control file sequential read | está esperando para acessar blocos do arquivo de controle. |
control file parallel write | está
esperando que termine sua requisição de E/S em paralelo para os arquivos de controle. |
log buffer space | está
esperando por espaço livre no buffer do log. (geralmente acontece quando as aplicações produzem redo (imagem anterior à alteração de algum registro do banco) mais rápido que o processo de descarregamento dos buffers de log em disco conseguem consumí-los. |
log file sequential read | está esperando para trazer blocos do arquivo de log ativo para memória. |
log file parallel write | está esperando para escrever blocos para um grupo de arquivos de log ativos. |
log file sync | está
esperando que processo responsável pela escrita de log termine de escrever os buffers para o disco. |
db file scattered read | emitiu
uma requisição de E/S para ler uma série de blocos contíguos de um arquivo de dados para a área de buffer e está esperando a operação completar. Tipicamente nas consultas (full scan) de índices e tabelas. |
db file sequential read | emitiu
uma requisição de E/S para ler um bloco de um arquivo de dados para a área de buffer e está esperando a operação completar. |
db file parallel read | emitiu
múltiplas requisições de E/S em paralelo para ler blocos de arquivos de dados para a área de buffer e está esperando que todas as operações se completem. |
db file parallel write | emitiu
múltiplas requisições de descarregamento dos buffers para o disco está
esperando que todas as operações completem. |
direct path read, direct path write | emitiu
requisições assíncronas de E/S que não passam pelos buffers e está esperando que todas as operações completem. É um evento típico de operações de classificação. |
sábado, 8 de março de 2014
referencias
Documentação 11G
GPO
http://www.ora-code.com/
http://tahiti.oracle.com/runningoracle.com
Psoug.org
Oracle Base
http://ss64.com/ora/
Guias certificação OCA 11G
certificacaobd.com.br
Exames
Certificação Oracle- dicas
http://fabiodba.blogspot.com/
brunors.com
Scripts
Scripts úteis
Estudo dia a dia
http://www.datadisk.co.uk/#
Oracle Base
Recuperações diversas (Banco)
Arup Nanda
http://www.wellingtonprado.com/
AlejandroVargas
https://blogs.oracle.com/
Burlesonhttp://www.oraclehome.com.br/
http://eduardolegatti.blogspot.com/
http://kb.paxtecnologia.com.br
http://blog.gaudencio.net.br
http://www.oracle.com/technetwork
http://flaviosoares.com/
http://www.fabioprado.net/
http://felipe.fortaltec.com.br/blog/
http://allthingsoracle.com/
http://databaseguard.blogspot.com/
https://sites.google.com/site/telodba/
http://www.diaadiaoracle.com.br/wordpress/
Dia a dia na T.I. [Vivência de um DBA
http://www.rodrigoalmeida.net/blog/tag/banco/
dbasolutions
http://oraclemais.blogspot.com/
http://ebsdicas.blogspot.com/
beingoracleappsdba
http://www.dbatutor.com/
ACES
http://www.gokhanatil.com/
OEBS Querys uteis -
http://glufke.net/oracle
runningoracle.com - APPS DBA
http://www.idevelopment.info/
dbasolutions
http://doganay.wordpress.com/
Unix
Toolbox
http://ss64.com
Outros
http://valteraquino.blogspot.com/
Assinar:
Postagens (Atom)
-
Verificar Jobs do Oracle desc DBA_SCHEDULER_JOB_RUN_DETAILS ; SQL> desc DBA_SCHEDULER_JOB_RUN_DETAILS ; Name ...
-
1 - TABELA com 50GB na sysaux Motivo - Armazena informações de snapshots do awr (automatic workload repository), que são relativos a relató...
-
Analisando SQL traces em Bancos de Dados Oracle - Parte 1 Fonte: http://www.fabioprado.net/2013/09/analisando-traces-em-bancos-de-da...