[Q]怎麼樣查詢特殊字符,如通配符%與_
[Q]如何插入單引號到數據庫表中
[Q]怎樣設置事務一致性
[Q]怎麼樣利用光標更新數據
[Q]怎樣自定義異常
[Q]十進制與十六進制的轉換
[Q]能不能介紹SYS_CONTEXT的詳細用法
[Q]怎麼得到今天是星期幾,還關於其它日期函數用法
[Q]隨機抽取前N條記錄的問題
[Q]抽取從N行到M行的記錄,如從20行到30行的記錄
[Q]怎麼樣抽取重複記錄
[Q]怎麼樣設置自治事務
[Q]怎麼樣在過程當中暫停指定時間
[Q]怎麼樣快速計算事務的時間與日誌量
[Q]怎樣建立臨時表
[Q]怎麼樣在PL/SQL中執行DDL語句
[Q]怎麼樣獲取IP地址
[Q]怎麼樣加密存儲過程
[Q]怎麼樣在ORACLE中定時運行存儲過程
[Q]怎麼樣從數據庫中得到毫秒
[Q]若是存在就更新,不存在就插入能夠用一個語句實現嗎
[Q]怎麼實現左聯,右聯與外聯
[Q]怎麼實現一條記錄根據條件多表插入
[Q]如何實現行列轉換
[Q]怎麼樣實現分組取前N條記錄
[Q]怎麼樣把相鄰記錄合併到一條記錄
[Q]如何取得一列中第N大的值?
[Q]怎麼樣把查詢內容輸出到文本
[Q]怎麼設置存儲過程的調用者權限
[Q] 如何在SQL*PLUS環境中執行OS命令?
[Q]怎麼快速得到用戶下每一個表或表分區的記錄數
[Q]怎麼在Oracle中發郵件
[Q]怎麼樣在Oracle中寫操做系統文件,如寫日誌java
解答:
[Q]怎麼樣查詢特殊字符,如通配符%與_
[A]select * from table where name like 'A\_%' escape '\'linux
[Q]如何插入單引號到數據庫表中
[A]能夠用ASCII碼處理,其它特殊字符如&也同樣,如
insert into t values('i'||chr(39)||'m'); -- chr(39)表明字符'
或者用兩個單引號表示一個
or insert into t values('I''m'); -- 兩個''能夠表示一個'sql
[Q]怎樣設置事務一致性
[A]set transaction [isolation level] read committed; 默認語句級一致性
set transaction [isolation level] serializable;
read only; 事務級一致性數據庫
[Q]怎麼樣利用光標更新數據
[A]cursor c1 is
select * from tablename
where name is null for update [of column]
……
update tablename set column = ……
where current of c1;windows
[Q]怎樣自定義異常
[A] pragma_exception_init(exception_name,error_number);
若是當即拋出異常
raise_application_error(error_number,error_msg,true|false);
其中number從-20000到-20999,錯誤信息最大2048B
異常變量
SQLCODE 錯誤代碼
SQLERRM 錯誤信息服務器
[Q]十進制與十六進制的轉換
[A]8i以上版本:
to_char(100,'XX')
to_number('4D','XX')
8i如下的進制之間的轉換參考以下腳本
create or replace function to_base( p_dec in number, p_base in number )
return varchar2
is
l_str varchar2(255) default NULL;
l_num number default p_dec;
l_hex varchar2(16) default '0123456789ABCDEF';
begin
if ( p_dec is null or p_base is null ) then
return null;
end if;
if ( trunc(p_dec) <> p_dec OR p_dec < 0 ) then
raise PROGRAM_ERROR;
end if;
loop
l_str := substr( l_hex, mod(l_num,p_base)+1, 1 ) || l_str;
l_num := trunc( l_num/p_base );
exit when ( l_num = 0 );
end loop;
return l_str;
end to_base;
/
create or replace function to_dec
( p_str in varchar2,
p_from_base in number default 16 ) return number
is
l_num number default 0;
l_hex varchar2(16) default '0123456789ABCDEF';
begin
if ( p_str is null or p_from_base is null ) then
return null;
end if;
for i in 1 .. length(p_str) loop
l_num := l_num * p_from_base + instr(l_hex,upper(substr(p_str,i,1)))-1;
end loop;
return l_num;
end to_dec;
/
create or replace function to_hex( p_dec in number ) return varchar2
is
begin
return to_base( p_dec, 16 );
end to_hex;
/
create or replace function to_bin( p_dec in number ) return varchar2
is
begin
return to_base( p_dec, 2 );
end to_bin;
/
create or replace function to_oct( p_dec in number ) return varchar2
is
begin
return to_base( p_dec, 8 );
end to_oct;
/session
[Q]能不能介紹SYS_CONTEXT的詳細用法
[A]利用如下的查詢,你就明白了
select
SYS_CONTEXT('USERENV','TERMINAL') terminal,
SYS_CONTEXT('USERENV','LANGUAGE') language,
SYS_CONTEXT('USERENV','SESSIONID') sessionid,
SYS_CONTEXT('USERENV','INSTANCE') instance,
SYS_CONTEXT('USERENV','ENTRYID') entryid,
SYS_CONTEXT('USERENV','ISDBA') isdba,
SYS_CONTEXT('USERENV','NLS_TERRITORY') nls_territory,
SYS_CONTEXT('USERENV','NLS_CURRENCY') nls_currency,
SYS_CONTEXT('USERENV','NLS_CALENDAR') nls_calendar,
SYS_CONTEXT('USERENV','NLS_DATE_FORMAT') nls_date_format,
SYS_CONTEXT('USERENV','NLS_DATE_LANGUAGE') nls_date_language,
SYS_CONTEXT('USERENV','NLS_SORT') nls_sort,
SYS_CONTEXT('USERENV','CURRENT_USER') current_user,
SYS_CONTEXT('USERENV','CURRENT_USERID') current_userid,
SYS_CONTEXT('USERENV','SESSION_USER') session_user,
SYS_CONTEXT('USERENV','SESSION_USERID') session_userid,
SYS_CONTEXT('USERENV','PROXY_USER') proxy_user,
SYS_CONTEXT('USERENV','PROXY_USERID') proxy_userid,
SYS_CONTEXT('USERENV','DB_DOMAIN') db_domain,
SYS_CONTEXT('USERENV','DB_NAME') db_name,
SYS_CONTEXT('USERENV','HOST') host,
SYS_CONTEXT('USERENV','OS_USER') os_user,
SYS_CONTEXT('USERENV','EXTERNAL_NAME') external_name,
SYS_CONTEXT('USERENV','IP_ADDRESS') ip_address,
SYS_CONTEXT('USERENV','NETWORK_PROTOCOL') network_protocol,
SYS_CONTEXT('USERENV','BG_JOB_ID') bg_job_id,
SYS_CONTEXT('USERENV','FG_JOB_ID') fg_job_id,
SYS_CONTEXT('USERENV','AUTHENTICATION_TYPE') authentication_type,
SYS_CONTEXT('USERENV','AUTHENTICATION_DATA') authentication_data
from dualoracle
[Q]怎麼得到今天是星期幾,還關於其它日期函數用法
[A]能夠用to_char來解決,如
select to_char(to_date('2002-08-26','yyyy-mm-dd'),'day') from dual;
在獲取以前能夠設置日期語言,如
ALTER SESSION SET NLS_DATE_LANGUAGE='AMERICAN';
還能夠在函數中指定
select to_char(to_date('2002-08-26','yyyy-mm-dd'),'day','NLS_DATE_LANGUAGE = American') from dual;
其它更多用法,能夠參考to_char與to_date函數
如得到完整的時間格式
select to_char(sysdate,'yyyy-mm-dd hh24:mi:ss') from dual;
隨便介紹幾個其它函數的用法:
本月的天數
SELECT to_char(last_day(SYSDATE),'dd') days FROM dual
今年的天數
select add_months(trunc(sysdate,'year'), 12) - trunc(sysdate,'year') from dual
下個星期一的日期
SELECT Next_day(SYSDATE,'monday') FROM dualapp
[Q]隨機抽取前N條記錄的問題
[A]8i以上版本
select * from (select * from tablename order by sys_guid()) where rownum < N;
select * from (select * from tablename order by dbms_random.value) where rownum< N;
注:dbms_random包須要手工安裝,位於$ORACLE_HOME/rdbms/admin/dbmsrand.sql
dbms_random.value(100,200)能夠產生100到200範圍的隨機數dom
[Q]抽取從N行到M行的記錄,如從20行到30行的記錄
[A]select * from (select rownum id,t.* from table) where id between N and M;
[Q]怎麼樣抽取重複記錄
[A]select * from table t1 where where t1.rowed !=
(select max(rowed) from table t2
where t1.id=t2.id and t1.name=t2.name)
或者
select count(*), t.col_a,t.col_b from table t
group by col_a,col_b
having count(*)>1
若是想刪除重複記錄,能夠把第一個語句的select替換爲delete
[Q]怎麼樣設置自治事務
[A]8i以上版本,不影響主事務
pragma autonomous_transaction;
……
commit|rollback;
[Q]怎麼樣在過程當中暫停指定時間
[A]DBMS_LOCK包的sleep過程
如:dbms_lock.sleep(5);表示暫停5秒。
[Q]怎麼樣快速計算事務的時間與日誌量
[A]能夠採用相似以下的腳本
DECLARE
start_time NUMBER;
end_time NUMBER;
start_redo_size NUMBER;
end_redo_size NUMBER;
BEGIN
start_time := dbms_utility.get_time;
SELECT VALUE INTO start_redo_size FROM v$mystat m,v$statname s
WHERE m.STATISTIC#=s.STATISTIC#
AND s.NAME='redo size';
--transaction start
INSERT INTO t1
SELECT * FROM All_Objects;
--other dml statement
COMMIT;
end_time := dbms_utility.get_time;
SELECT VALUE INTO end_redo_size FROM v$mystat m,v$statname s
WHERE m.STATISTIC#=s.STATISTIC#
AND s.NAME='redo size';
dbms_output.put_line('Escape Time:'||to_char(end_time-start_time)||' centiseconds');
dbms_output.put_line('Redo Size:'||to_char(end_redo_size-start_redo_size)||' bytes');
END;
[Q]怎樣建立臨時表
[A]8i以上版本
create global temporary tablename(column list)
on commit preserve rows; --提交保留數據 會話臨時表
on commit delete rows; --提交刪除數據 事務臨時表
臨時表是相對於會話的,別的會話看不到該會話的數據。
[Q]怎麼樣在PL/SQL中執行DDL語句
[A]一、8i如下版本dbms_sql包
二、8i以上版本還能夠用
execute immediate sql;
dbms_utility.exec_ddl_statement('sql');
[Q]怎麼樣獲取IP地址
[A]服務器(817以上):utl_inaddr.get_host_address
客戶端:sys_context('userenv','ip_address')
[Q]怎麼樣加密存儲過程
[A]用wrap命令,如(假定你的存儲過程保存爲a.sql)
wrap iname=a.sql
PL/SQL Wrapper: Release 8.1.7.0.0 - Production on Tue Nov 27 22:26:48 2001
Copyright (c) Oracle Corporation 1993, 2000. All Rights Reserved.
Processing a.sql to a.plb
提示a.sql轉換爲a.plb,這就是加密了的腳本,執行a.plb便可生成加密了的存儲過程
[Q]怎麼樣在ORACLE中定時運行存儲過程
[A]能夠利用dbms_job包來定時運行做業,如執行存儲過程,一個簡單的例子,提交一個做業:
VARIABLE jobno number;
BEGIN
DBMS_JOB.SUBMIT(:jobno, 'ur_procedure;',SYSDATE,'SYSDATE + 1');
commit;
END;
以後,就能夠用如下語句查詢已經提交的做業
select * from user_jobs;
[Q]怎麼樣從數據庫中得到毫秒
[A]9i以上版本,有一個timestamp類型得到毫秒,如
SQL>select to_char(systimestamp,'yyyy-mm-dd hh24:mi:ssxff') time1,
to_char(current_timestamp) time2 from dual;
TIME1 TIME2
----------------------------- ----------------------------------------------------------------
2003-10-24 10:48:45.656000 24-OCT-03 10.48.45.656000 AM +08:00
能夠看到,毫秒在to_char中對應的是FF。
8i以上版本能夠建立一個以下的java函數
SQL>create or replace and compile
java source
named "MyTimestamp"
as
import java.lang.String;
import java.sql.Timestamp;
public class MyTimestamp
{
public static String getTimestamp()
{
return(new Timestamp(System.currentTimeMillis())).toString();
}
};
SQL>java created.
注:注意java的語法,注意大小寫
SQL>create or replace function my_timestamp return varchar2
as language java
name 'MyTimestamp.getTimestamp() return java.lang.String';
/
SQL>function created.
SQL>select my_timestamp,to_char(sysdate,'yyyy-mm-dd hh24:mi:ss') ORACLE_TIME from dual;
MY_TIMESTAMP ORACLE_TIME
------------------------ -------------------
2003-03-17 19:15:59.688 2003-03-17 19:15:59
若是隻想得到1/100秒(hsecs),還能夠利用dbms_utility.get_time
[Q]若是存在就更新,不存在就插入能夠用一個語句實現嗎
[A]9i已經支持了,是Merge,可是隻支持select子查詢,
若是是單條數據記錄,能夠寫做select …… from dual的子查詢。
語法爲:
MERGE INTO table
USING data_source
ON (condition)
WHEN MATCHED THEN update_clause
WHEN NOT MATCHED THEN insert_clause;
如
MERGE INTO course c
USING (SELECT course_name, period,
course_hours
FROM course_updates) cu
ON (c.course_name = cu.course_name
AND c.period = cu.period)
WHEN MATCHED THEN
UPDATE
SET c.course_hours = cu.course_hours
WHEN NOT MATCHED THEN
INSERT (c.course_name, c.period,
c.course_hours)
VALUES (cu.course_name, cu.period,
cu.course_hours);
[Q]怎麼實現左聯,右聯與外聯
[A]在9i之前能夠這麼寫:
左聯:
select a.id,a.name,b.address from a,b
where a.id=b.id(+)
右聯:
select a.id,a.name,b.address from a,b
where a.id(+)=b.id
外聯
SELECT a.id,a.name,b.address
FROM a,b
WHERE a.id = b.id(+)
UNION
SELECT b.id,'' name,b.address
FROM b
WHERE NOT EXISTS (
SELECT * FROM a
WHERE a.id = b.id);
在9i以上,已經開始支持SQL99標準,因此,以上語句能夠寫成:
默認內部聯結:
select a.id,a.name,b.address,c.subject
from (a inner join b on a.id=b.id)
inner join c on b.name = c.name
where other_clause
左聯
select a.id,a.name,b.address
from a left outer join b on a.id=b.id
where other_clause
右聯
select a.id,a.name,b.address
from a right outer join b on a.id=b.id
where other_clause
外聯
select a.id,a.name,b.address
from a full outer join b on a.id=b.id
where other_clause
or
select a.id,a.name,b.address
from a full outer join b using (id)
where other_clause
[Q]怎麼實現一條記錄根據條件多表插入
[A]9i以上能夠經過Insert all語句完成,僅僅是一個語句,如:
INSERT ALL
WHEN (id=1) THEN
INTO table_1 (id, name)
values(id,name)
WHEN (id=2) THEN
INTO table_2 (id, name)
values(id,name)
ELSE
INTO table_other (id, name)
values(id, name)
SELECT id,name
FROM a;
若是沒有條件的話,則完成每一個表的插入,如
INSERT ALL
INTO table_1 (id, name)
values(id,name)
INTO table_2 (id, name)
values(id,name)
INTO table_other (id, name)
values(id, name)
SELECT id,name
FROM a;
[Q]如何實現行列轉換
[A]一、固定列數的行列轉換
如
student subject grade
---------------------------
student1 語文 80
student1 數學 70
student1 英語 60
student2 語文 90
student2 數學 80
student2 英語 100
……
轉換爲
語文 數學 英語
student1 80 70 60
student2 90 80 100
……
語句以下:
select student,sum(decode(subject,'語文', grade,null)) "語文",
sum(decode(subject,'數學', grade,null)) "數學",
sum(decode(subject,'英語', grade,null)) "英語"
from table
group by student
二、不定列行列轉換
如
c1 c2
--------------
1 我
1 是
1 誰
2 知
2 道
3 不
……
轉換爲
1 我是誰
2 知道
3 不
這一類型的轉換必須藉助於PL/SQL來完成,這裏給一個例子
CREATE OR REPLACE FUNCTION get_c2(tmp_c1 NUMBER)
RETURN VARCHAR2
IS
Col_c2 VARCHAR2(4000);
BEGIN
FOR cur IN (SELECT c2 FROM t WHERE c1=tmp_c1) LOOP
Col_c2 := Col_c2||cur.c2;
END LOOP;
Col_c2 := rtrim(Col_c2,1);
RETURN Col_c2;
END;
/
SQL> select distinct c1 ,get_c2(c1) cc2 from table;便可
[Q]怎麼樣實現分組取前N條記錄
[A]8i以上版本,利用分析函數
如獲取每一個部門薪水前三名的員工或每一個班成績前三名的學生。
Select * from
(select depno,ename,sal,row_number() over (partition by depno
order by sal desc) rn
from emp)
where rn<=3
[Q]怎麼樣把相鄰記錄合併到一條記錄
[A]8i以上版本,分析函數lag與lead能夠提取後一條或前一天記錄到本記錄。
Select deptno,ename,hiredate,lag(hiredate,1,null) over
(partition by deptno over by hiredate,ename) last_hire
from emp
order by depno,hiredate
[Q]如何取得一列中第N大的值?
[A]select * from
(select t.*,dense_rank() over (order by t2 desc) rank from t)
where rank = &N;
[Q]怎麼樣把查詢內容輸出到文本
[A]a.控制語句,如set heading off
b.spool 完整文件名
c.查詢語句
……
d.spool off
[Q]怎麼設置存儲過程的調用者權限
[A]普通存儲過程都是全部者權限,若是想設置調用者權限,請參考以下語句
create or replace
procedure ……()
AUTHID CURRENT_USER
As
begin
……
end;
[Q] 如何在SQL*PLUS環境中執行OS命令?
[A] 好比進入了SQLPLUS,啓動了數據庫,突然想起監聽尚未啓動,此時不用退出SQLPLUS,也不用另外起一個命令行窗口,直接輸入:
SQL> host lsntctl start
或者unix/linux平臺下
SQL>!<OS command>
windows平臺下
SQL>$<OS command>
總結:HOST <OS command>能夠直接執行OS命令。
備註:cd命令沒法正確執行。
[Q]怎麼快速得到用戶下每一個表或表分區的記錄數
[A]能夠分析該用戶,而後查詢user_tables字典,或者採用以下腳本便可
SET SERVEROUTPUT ON SIZE 20000
DECLARE
miCount INTEGER;
BEGIN
FOR c_tab IN (SELECT table_name FROM user_tables) LOOP
EXECUTE IMMEDIATE 'select count(*) from "' || c_tab.table_name || '"' into miCount;
dbms_output.put_line(rpad(c_tab.table_name,30,'.') || lpad(miCount,10,'.'));
--if it is partition table
SELECT COUNT(*) INTO miCount FROM User_Part_Tables WHERE table_name = c_tab.table_name;
IF miCount >0 THEN
FOR c_part IN (SELECT partition_name FROM user_tab_partitions WHERE table_name = c_tab.table_name) LOOP
EXECUTE IMMEDIATE 'select count(*) from ' || c_tab.table_name || ' partition (' || c_part.partition_name || ')'
INTO miCount;
dbms_output.put_line(' '||rpad(c_part.partition_name,30,'.') || lpad(miCount, 10,'.'));
END LOOP;
END IF;
END LOOP;
END;
[Q]怎麼在Oracle中發郵件
[A]能夠利用utl_smtp包發郵件,如下是一個發送簡單郵件的例子程序
/****************************************************************************
parameter: Rcpter in varchar2 接收者郵箱
Mail_Content in Varchar2 郵件內容
desc: ·發送郵件到指定郵箱
·只能指定一個郵箱,若是須要發送到多個郵箱,須要另外的輔助程序
****************************************************************************/
CREATE OR REPLACE PROCEDURE sp_send_mail( rcpter IN VARCHAR2,
mail_content IN VARCHAR2)
IS
conn utl_smtp.connection;
--write title
PROCEDURE send_header(NAME IN VARCHAR2, HEADER IN VARCHAR2) AS
BEGIN
utl_smtp.write_data(conn, NAME||': '|| HEADER||utl_tcp.CRLF);
END;
BEGIN
--opne connect
conn := utl_smtp.open_connection('smtp.com');
utl_smtp.helo(conn, 'oracle');
utl_smtp.mail(conn, 'oracle info');
utl_smtp.rcpt(conn, Rcpter);
utl_smtp.open_data(conn);
--write title
send_header('From', 'Oracle Database');
send_header('To', '"Recipient" <'||rcpter||'>');
send_header('Subject', 'DB Info');
--write mail content
utl_smtp.write_data(conn, utl_tcp.crlf || mail_content);
--close connect
utl_smtp.close_data(conn);
utl_smtp.quit(conn);
EXCEPTION
WHEN utl_smtp.transient_error OR utl_smtp.permanent_error THEN
BEGIN
utl_smtp.quit(conn);
EXCEPTION
WHEN OTHERS THEN
NULL;
END;
WHEN OTHERS THEN
NULL;
END sp_send_mail;
[Q]怎麼樣在Oracle中寫操做系統文件,如寫日誌 [A]能夠利用utl_file包,可是,在此以前,要注意設置好Utl_file_dir初始化參數 /************************************************************************** parameter:textContext in varchar2 日誌內容 desc: ·寫日誌,把內容記到服務器指定目錄下 ·必須配置Utl_file_dir初始化參數,並保證日誌路徑與Utl_file_dir路徑一致或者是其中一個 ****************************************************************************/ CREATE OR REPLACE PROCEDURE sp_Write_log(text_context VARCHAR2) IS file_handle utl_file.file_type; Write_content VARCHAR2(1024); Write_file_name VARCHAR2(50); BEGIN --open file write_file_name := 'db_alert.log'; file_handle := utl_file.fopen('/u01/logs',write_file_name,'a'); write_content := to_char(SYSDATE,'yyyy-mm-dd hh24:mi:ss')||'||'||text_context; --write file IF utl_file.is_open(file_handle) THEN utl_file.put_line(file_handle,write_content); END IF; --close file utl_file.fclose(file_handle); EXCEPTION WHEN OTHERS THEN BEGIN IF utl_file.is_open(file_handle) THEN utl_file.fclose(file_handle); END IF; EXCEPTION WHEN OTHERS THEN NULL; END; END sp_Write_log;