달력

5

« 2024/5 »

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
2011. 4. 20. 15:12

줄->열 변환 Work/PostgreSQL2011. 4. 20. 15:12

Postgresql 의 특성 중 하나가 배열처리인 것 같다.
아래처럼 경악스러운 기능이 있다.
-----------------------------------------
-bash-3.2$ psql
비밀번호:
Welcome to psql 8.1.22 (server 9.0.3), the PostgreSQL interactive terminal.
 
Type:  \copyright for distribution terms
       \h for help with SQL commands
       \? for help with psql commands
       \g or terminate with semicolon to execute query
       \q to quit
 
WARNING:  You are connected to a server with major version 9.0,
but your psql client is major version 8.1.  Some backslash commands,
such as \d, might not work properly.
 
postgres=#
postgres=#
postgres=# select unnest(string_to_array('111,222,333,444,555', ','));
 unnest
--------
 111
 222
 333
 444
 555
(5건 있음)
postgres=#
-----------------------------------------

이렇게 놀라운 기능이란... 0_0
:
Posted by Elick
2011. 4. 12. 13:47

Postgresql 중앙값 Work/PostgreSQL2011. 4. 12. 13:47

중앙값(median)은 어떤 주어진 값들을 정렬했을 때 가장 중앙에 위치하는 값을 의미한다. 예를 들어 1, 2, 100의 세 값이 있을 때, 2가 가장 중앙에 있기 때문에 2가 중앙값이다.
값이 짝수개일 때에는 중앙값이 유일하지 않고 두 개가 될 수도 있다. 이 경우 그 두 값의 평균을 취한다. 예를 들어 1, 10, 90, 200 네 수의 중앙값은 10과 90의 평균인 50이 된다.

Postgresql에서 중앙값 구현은 사용자 함수로 생성해서 사용한다.

--------  사용자 함수 생성 --------
 
CREATE OR REPLACE FUNCTION _final_median(numeric[])
   RETURNS numeric AS
$$
   SELECT AVG(val)
   FROM (
     SELECT val
     FROM unnest($1) val
     ORDER BY 1
     LIMIT  2 - MOD(array_upper($1, 1), 2)
     OFFSET CEIL(array_upper($1, 1) / 2.0) - 1
   ) sub;
$$
LANGUAGE 'sql' IMMUTABLE;
  
CREATE AGGREGATE median(numeric) (
  SFUNC=array_append,
  STYPE=numeric[],
  FINALFUNC=_final_median,
  INITCOND='{}'
);


--------  사용예 --------
SELECT median(AA)
FROM (
SELECT 1 AA UNION ALL
SELECT 2 UNION ALL
SELECT 3 UNION ALL
SELECT 4 UNION ALL
SELECT 5 UNION ALL
SELECT 6 UNION ALL
SELECT 7
) A
-- Result : 4.0000000000000000
 
SELECT median(AA)
FROM (
SELECT 1 AA UNION ALL
--SELECT 2 UNION ALL
SELECT 3 UNION ALL
SELECT 4 UNION ALL
SELECT 5 UNION ALL
SELECT 6 UNION ALL
SELECT 7
) A
-- Result : 4.5000000000000000
:
Posted by Elick
2011. 4. 12. 13:42

Postgresql 8.3.3 manual Work/PostgreSQL2011. 4. 12. 13:42

http://www.postgresplus.co.kr/man/index.html#AEN3

위 link가 내가 찾은 가장 괜찮은 Postgresql manual 일 듯 하다.
:
Posted by Elick
2011. 4. 12. 13:37

Oracle 복구 Work/ORACLE2011. 4. 12. 13:37

최근에 겪은 이슈이다.

------------ xxx.trc-----------------
*** SESSION ID:(20.8) 2011-04-11 23:19:12.000
*** 2011-04-11 23:19:12.000
ksedmp: internal or fatal error
ORA-01114: 7 파일에 블록을 기록하는데 IO 오류입니다 (블록 번호 2620040)
ORA-27069: skgfdisp: I/O을 시도시 파일의 범위를 넘었습니다
OSD-04026: 부적합한 매개변수가 전달되었습니다. (OS 2620040)
ORA-01114: 7 파일에 블록을 기록하는데 IO 오류입니다 (블록 번호 2620040)
ORA-27069: skgfdisp: I/O을 시도시 파일의 범위를 넘었습니다
OSD-04026: 부적합한 매개변수가 전달되었습니다. (OS 2620040)
ORA-01114: 7 파일에 블록을 기록하는데 IO 오류입니다 (블록 번호 2620040)
ORA-27069: skgfdisp: I/O을 시도시 파일의 범위를 넘었습니다
OSD-04026: 부적합한 매개변수가 전달되었습니다. (OS 2620040)
ORA-01114: 7 파일에 블록을 기록하는데 IO 오류입니다 (블록 번호 2620040)
ORA-27069: skgfdisp: I/O을 시도시 파일의 범위를 넘었습니다
OSD-04026: 부적합한 매개변수가 전달되었습니다. (OS 2620040)
No current SQL statement being executed.
------------ xxx.trc-----------------

위의 에러가 발생했고...

대처를 적절히 하지 못해서 hot backup 된 것을 바로 replace 하기로 결정.
redo log 없고, controlfile, dbf 만 있는 상황....
복구시도를 했으나 번번이 실패...


과거에는 alter database open resetlogs 로 바로 복구되었는데 어찌된 일인지 아래처럼 안된다.

-----------  sqlplus --------------------
SQL> alter database open resetlogs;
alter database open resetlogs
*
1행에 오류:
ORA-01195: 1 파일의 온라인 백업은 일관성을 갖기위해 더 많은 복구가 필요로 합니다
ORA-01110: 1 데이터 파일:
SQL> 
-----------  sqlplus --------------------


하지만 pfile에 _ALLOW_RESETLOGS_CORRUPTION=TRUE option 적용 후 resetlogs 로 open.이 가능했다.

아.. 다행이다.. 

참고 url
http://practicalappsdba.wordpress.com/2008/04/01/how-to-recover-and-open-the-database-if-the-archive-log-required-for-recovery-is-missing/ 


주요 내용은 아래와 같다.

1) Set _ALLOW_RESETLOGS_CORRUPTION=TRUE in init.ora file.
2) Startup Mount
3) Recover database
4) Alter database open resetlogs.
5) reset undo_management to “manual” in init.ora file.
6) startup database
7) Create new undo tablespace
changed undo_management to “AUTO” and undo_tablespace to “NewTablespace”
9) Bounce database. 

:
Posted by Elick
2011. 3. 25. 17:23

Windows7 BCDEDIT Work/Etc2011. 3. 25. 17:23

- BCDEDIT의 기본
bcdedit의 기본은 역시 관리자 권한입니다. 관리자 권한으로 명령 프롬프트를 실행해야 bcdedit을 사용할 수 있습니다. 그리고 뒤에 /? 붙이시면 도움말이 나오니 궁금한 점이 있으시면 도움말을 잘 활용해보세요.


- 비스타, 세븐 부팅메뉴 추가하기
기존 항목을 복사한 다음 일부만 수정해주는 방법이 있고, 완전 새로 만드는 방법이 있습니다. 또한 윈도우 7에서는 Bcdboot 명령어를 이용해 간단히 처리할 수도 있습니다. 하지만 여기서는 수동으로 만드는 방법에 대해 설명드리겠습니다. bcdedit 사용법에 대해 설명드리는 글이니까요. 추가할 윈도우 7은 E 드라이브에 존재한다고 가정하겠습니다.

bcdedit /create /application OSLOADER /d "Windows 7 Ultimate K x64"

위 예처럼 /create /application OSLOADER 를 이용하면 윈도우 부팅 로더를 하나 만들 수 있습니다. /d 뒤에는 메뉴 이름을 적어주시면 됩니다. 이렇게 명령어를 넣으면 {132b80fe-790a-11df-b168-a80a0ebf9332} 처럼 생긴 {GUID}가 반환되는데 (이름은 랜덤으로 생성) 아래 명렁어부터는 이 부분을 {GUID} 라고 적겠습니다. 실제로 작업하실 때는 {GUID} 부분에 {132b80fe-790a-11df-b168-a80a0ebf9332} 처럼 직접 입력하셔야 합니다.

bcdedit /set {GUID} device partition=E:
bcdedit /set {GUID} osdevice partition=E:
bcdedit /set {GUID} path \Windows\system32\winload.exe
bcdedit /set {GUID} locale ko-KR
bcdedit /set {GUID} inherit {bootloadersettings}
bcdedit /set {GUID} recoverysequence {메롱}
bcdedit /set {GUID} recoveryenabled Yes
bcdedit /set {GUID} systemroot \Windows
bcdedit /set {GUID} nx OptIn
bcdedit /displayorder {GUID} /addlast

이렇게 하시면 E 드라이브에 있는 윈도우 7이 부팅 메뉴에 등록됩니다. 파란색 부분은 F8 복구모드에 관한 내용인데 일단 생략하세요. 뒤쪽에 가서 다루겠습니다.


- 윈도우 XP 부팅메뉴 추가하기
XP는 메뉴만 추가한다고 되는게 아니고 NTLDR, NTDETECT.COM, BOOT.INI 파일도 시스템 파티션에 복사를 해와야 합니다. 이건 여기서 다루지 않고 예전에 포스팅했던 글로 대체하겠습니다.



- VHD 파일 부팅메뉴 추가하기
VHD 파일도 처음에 설명드렸던 방법과 비슷합니다. E 드라이브 VHD 폴더 안에 win7.vhd 파일이 존재한다고 가정하고 진행하겠습니다.

bcdedit /create /application OSLOADER /d "Windows 7 VHD Boot"

bcdedit /set {GUID} device vhd=[E:]\vhd\win7.vhd
bcdedit /set {GUID} osdevice vhd=[E:]\vhd\win7.vhd
bcdedit /set {GUID} path \Windows\system32\winload.exe
bcdedit /set {GUID} locale ko-KR
bcdedit /set {GUID} inherit {bootloadersettings}
bcdedit /set {GUID} systemroot \Windows
bcdedit /set {GUID} nx OptIn
bcdedit /set {GUID} detecthal Yes
bcdedit /displayorder {GUID} /addlast

여기서는 F8 복구모드 항목을 빼버렸습니다. 그 이유는 나중에 설명드리겠습니다. detecthal Yes 정도만 추가되었다고 보시면 되겠네요.


- 항목 복사하기
제가 위에서 기존 항목을 복사한 다음 일부만 수정해주는 방법이 있다고 했는데 윈도우 7이 설치된 상태에서 윈도우 비스타를 추가하려는 경우 앞에서 설명드린 방법처럼 수동으로 일일이 만들어도 되겠지만 그냥 윈도우 7의 항목을 그대로 복사한 다음 경로만 수정해주셔도 별 문제는 없습니다.

bcdedit /copy {복사해올 항목의 GUID} /d "Windows Vista Ultimate K x64"

bcdedit /set {GUID} device partition=E:
bcdedit /set {GUID} osdevice partition=E:

이런 식으로 현재 C 드라이브에서 구동중인 윈도우 7 부팅항목을 그대로 하나 복사한 다음 E 드라이브에 존재하는 비스타를 위해 위치만 변경해주는 식으로 해도 됩니다.


- 이름 바꾸기
description 항목을 변경하시면 됩니다. 예를 들어 Windows 7 이라는 기본 영문 이름이 마음에 들지 않는다면

bcdedit /set {GUID} description "윈도우 7"


- 기본으로 부팅될 항목 설정
뭐 이런건 msconfig에서 하셔도 되겠지만...

bcdedit /default {GUID}


- 멀티부팅 시간 정하기

bcdedit /timeout 3


- 메뉴 순서 변경하기

bcdedit /displayorder {GUID1} {GUID2} {GUID3} {GUID4}

특정 항목만 지정해서 처음으로, 끝으로 보내려면 /addfirst, /addlast 등을 붙이면 됩니다.


- 메뉴 삭제하기

bcdedit /delete {GUID} /cleanup /f


- /enum all
중급자 분들은 이거 하나만 해보셔도 그동안 궁금해했던 부분들이 다 풀릴 것입니다. 여기에 모든 비밀이 다 숨겨져 있습니다.


- inherit
정확히는 잘 모르겠습니다. 상속이라고 하니 지정한 항목에서 속성을 물려받는다는 말 같은데... 별 필요는 없다고 봅니다.


- resumeobject
최대절전모드를 지정합니다. 여기에 나와있는 {GUID}의 내용을 직접 확인해보시려면

bcdedit /enum {GUID}

아래는 VMware에 설치된 윈도우 7의 resumeobject 항목의 예입니다.

최대 절전 모드에서 다시 시작
---------------------
identifier              {132b80fa-790a-11df-b168-a80a0ebf9332}
device                  partition=C:
path                    \Windows\system32\winresume.exe
description             Windows Resume Application
locale                  ko-KR
inherit                 {resumeloadersettings}
filedevice              partition=C:
filepath                \hiberfil.sys
pae                     Yes
debugoptionenabled      No

만약 최대절전모드를 사용하지 않는다면 resumeobject 항목은 필요가 없는 것이고 만약 필요한데 항목이 없다면 직접 위 예처럼 하나 만들어 주시면 되겠지요.

bcdedit /create /application RESUME /d "Windows Resume Application"

bcdedit /set {GUID} device partition=C:
bcdedit /set {GUID} path \Windows\system32\winresume.exe
bcdedit /set {GUID} locale ko-KR
bcdedit /set {GUID} inherit {resumeloadersettings}
bcdedit /set {GUID} filedevice partition=C:
bcdedit /set {GUID} filepath \hiberfil.sys
bcdedit /set {GUID} pae Yes
bcdedit /set {GUID} debugoptionenabled No

만약에 다른 RESUME 항목이 있다면 /copy 로 복사하거나 그놈을 직접 resumeobject 의 {GUID}로 지정해버려도 되겠습니다. 저는 최대절전모드를 사용하지 않으니 대충 이정도만 설명드리겠습니다.


- nx OptIn
DEP 설정입니다. OptIn이 기본값입니다. AlwaysOff 하시면 DEP를 끕니다.


- F8 복구모드 이야기
일반적으로 F8 복구모드는 있어야 정상인데 없는 경우 수동으로 등록시켜주시면 됩니다. 사실 이것도 알고 보니 별거 없었습니다. 아래 예는 VMware에 설치한 순수 윈도우 7 기준입니다.

Windows 부팅 로더
-------------------
identifier              {132b80fc-790a-11df-b168-a80a0ebf9332}
device                  ramdisk=[C:]\Recovery\132b80fc-790a-11df-b168-a80a0ebf93
32\Winre.wim,{132b80fd-790a-11df-b168-a80a0ebf9332}
path                    \windows\system32\winload.exe
description             Windows Recovery Environment
inherit                 {bootloadersettings}
osdevice                ramdisk=[C:]\Recovery\132b80fc-790a-11df-b168-a80a0ebf93
32\Winre.wim,{132b80fd-790a-11df-b168-a80a0ebf9332}
systemroot              \windows
nx                      OptIn
winpe                   Yes

장치 옵션
--------------
identifier              {132b80fd-790a-11df-b168-a80a0ebf9332}
description             Ramdisk Options
ramdisksdidevice        partition=C:
ramdisksdipath          \Recovery\132b80fc-790a-11df-b168-a80a0ebf9332\boot.sdi

결국 Recovery 폴더에 들어있는 Winre.wim 파일을 램디스크 옵션을 사용해 PE 부팅 시키는거죠.
만약 F8 복구모드가 없는 경우라면 아래 두 글을 참조하시면 해결될겁니다.

2010/03/03 - [Windows 7] - 윈도우 7 F8 컴퓨터 복구 모드가 없는 경우
2010/03/05 - [Windows 7] - 윈도우 7 F8 컴퓨터 복구 모드가 없는 경우 2탄

제가 VHD 부팅에서는 F8 복구모드 부분을 빼버렸다고 했습니다. 왜냐하면 VHD 안에 boot.sdi 파일이 들어있기 때문에 사실상 VHD에선 F8 복구모드를 이용할 수 없는게 정상이기 때문입니다. 굳이 이용하려면 boot.sdi 파일을 VHD 외부에 두고 램디스크 옵션을 만든 다음 VHD 안에 있는 WinRE.wim 파일을 로딩해야 합니다. 아니면 아예 둘다 바깥에 빼버리든가, F8 복구모드 따위 필요없고 직접 boot.wim 파일을 멀티부팅 메뉴에 등록해두는게 더 편하겠지요.


- BCD 새로 생성하기
BCD가 존재하지 않는 비어있는 파티션에 BCD를 생성하는 명령어입니다. 일단 보기좋게 BOOT 폴더를 하나 만드는게 좋겠죠. 저는 E 드라이브에 BOOT 폴더를 만들어 거기에 생성해보겠습니다.

md e:\boot
bcdedit /createstore e:\boot\bcd
bcdedit /store e:\boot\bcd /create {bootmgr} /d "Windows Boot Manager"
bcdedit /store e:\boot\bcd /set {bootmgr} device partition=E:
bcdedit /store e:\boot\bcd /set {bootmgr} locale ko-KR

딱 이정도만 해주시면 되는데 파일이 2개 필요합니다. 일단 bootmgr 파일이 E 드라이브 루트에 있어야겠지요? 또한 로케일을 ko-KR로 지정했다면 (메뉴 한글로 나오라고) bootmgr.exe.mui 파일을 e:\boot\ko-KR 폴더를 만들어 그 안에 복사해야 합니다. bootmgr.exe.mui 파일은 C:\Windows\Boot\PCAT\ko-KR 폴더 안에 들어있습니다.

그런데 윈도우 7 설치시 자동으로 만들어주는 BCD와 이렇게 수동으로 만든 BCD는 차이가 매우 큽니다. 자동으로 만들때는 잡다한 {memdiag}, {emssettings}, {dbgsettings}, {badmemory}, {globalsettings}, {bootloadersettings}, {hypervisorsettings}, {resumeloadersettings} 등이 생성되는데 수동으로 이렇게 만들면 그게 없으니까요. 하지만 제 생각에 이것들은 없어도 그만으로 보입니다.


- BCD 위치 지정
바로 위에서 설명드린 BCD 생성하기를 보면 /store 옵션이 있습니다. 현재 부팅해서 사용중인 윈도우의 BCD가 아니라 새로 생성하거나 백업해두었거나 DVD 부팅용 메뉴를 편집하려 한다면 /store 옵션을 붙여서 직접 BCD의 위치를 지정해서 편집하시면 됩니다.


- BCD 백업과 복원
마지막으로 BCD 설정을 파일로 백업하거나, 파일로부터 설정을 복구하는 방법입니다.

bcdedit /export e:\bcdbackup\bcd

물론 위 경우라면 E 드라이브에 backupbcd 폴더는 먼저 만들어놔야 합니다. 이렇게 하시면 현재 BCD 설정이 저 파일에 백업됩니다. 이게 단순히 BCD 파일을 복사하는 것과 차이가 있는지는 잘 모르겠습니다.

bcdedit /import e:\bcdbackup\bcd

위 백업파일로부터 BCD를 가져옵니다. 이때 기존 설정은 다 날아가고 새로 가져온 설정만 남게 됩니다.

원문 :  http://snoopybox.co.kr/1353
:
Posted by Elick


How to Setup Sqlplus for Most Efficient Use on Windows

Sqlplus command line or console version is actually more powerful and efficient than its Windows or GUI version.note1 The feature that brings the greatest convenience is probably being able to press UP key to recall previous commands. With Oracle11g, the Windows version is no longer available, making the console version more than just appealing, but essential. This article summarizes some tips you may find useful in using the console version. I assume your desktop OS is XP unless otherwise noted.

1. Create a shortcut in Start menu

In Windows Explorer, at C:\Documents and Settings\user\Start Menu (where user is you or "All Users"), create a shortcut named for instance "Sqlplus" pointing to %oracle_home%\bin\sqlplus.exe, and prepend cmd.exe /k. (The path is different in Windows 7; see bottom of this page.) So the shortcut target looks like this:

cmd /k d:\oracle\product\10.2.0\Db_2\bin\sqlplus.exe

Because of cmd /k, if you exit sqlplus, sometimes accidentally by ^C, the console window remains open instead of closing itself. So you can still see the result on screen.

If for any reason you need to set oracle_home and oracle_sid just for running this sqlplus, i.e. not wanting to set it in Control Panel, the command will be:cmd /k set oracle_home=d:\oracle\product\10.2.0\db_2& set oracle_sid=orcl& d:\oracle\product\10.2.0\db_2\bin\sqlplus (adjust paths as needed). If you think too many environment variables should be set, put them in a batch file and call the file on this command instead. For instance, c:\10g.bat & cmd /k d:\...

I normally set "Start in" folder to somewhere other than the default %oracle_home%\bin, such as d:\temp, so a spooled file goes there by default.

Once this shortcut is there, you can quickly launch Sqlplus by going to Start -> Sqlplus. If you want to launch it even faster, set a shortcut key for it.

2. Adjust shortcut properties

Screen colors are probably the most important, ergonomically speaking. In Properties window for this shortcut, go to Colors tab, I strongly suggest you choose black for Screen Text and very light color or white for Screen Background. Trust me on this advice! Do an experiment with two console windows, one with white text in black background and the other with black text in white or light color background (see below). Make sure text font is exactly the same in size and face. Stand some distance away. You'll find that the text in the second window looks much clearer and you can read faster. I think the reason is that white text lines have more visible tiny black gaps than black text lines have white gaps.

Eye strain test

c:\ C:\WINDOWS\System32\cmd.exec:\ C:\WINDOWS\System32\cmd.exe
D:\>od -x D:\oracle\product\10.2.0\db_1\bin\sqlplus.exe|head -5
0000000 5a4d 0090 0003 0000 0004 0000 ffff 0000
0000020 00b8 0000 0000 0000 0040 0000 0000 0000
0000040 0000 0000 0000 0000 0000 0000 0000 0000
0000060 0000 0000 0000 0000 0000 0000 00f8 0000
0000100 1f0e 0eba b400 cd09 b821 4c01 21cd 6854
D:\>od -x D:\oracle\product\10.2.0\db_1\bin\sqlplus.exe|head -5
0000000 5a4d 0090 0003 0000 0004 0000 ffff 0000
0000020 00b8 0000 0000 0000 0040 0000 0000 0000
0000040 0000 0000 0000 0000 0000 0000 0000 0000
0000060 0000 0000 0000 0000 0000 0000 00f8 0000
0000100 1f0e 0eba b400 cd09 b821 4c01 21cd 6854

Don't be discouraged by only 16 color choices. You can adjust Red, Green and Blue to fairly high numbers to get your favorite light color, such as 200-255-200 for light green, 255-255-200 for beige, etc.

Now go to Options tab. Check QuickEdit mode and Insert mode checkboxes. It makes copy and paste of text easier. (If you see somebody send an image of Sqlplus text, you know he/she is very computer un-savvy!)

Under Font, choose a small font but not too small to your vision. I like Lucida Console, and not Bold version of it.

Under Layout, set Width for both Screen buffer and Window sizes to the same number, I would say at least 100, up to the full width of your screen, but make sure the vertical scroll bar is still visible near the right edge and no horizontal scroll bar is shown at the bottom. On my 19-inch monitor using 10-point Lucida Console font, I can get 188 in screen width. Set Height for Screen Buffer to 2000, or at least 1000. The reason you want the Sqlplus screen as wide as you feel comfortable is so that you'll have less cluster in the query output.

3. Sqlplus setting

Default pagesize 14 is absolutely inadequate. I prefer 100 (except in case of very wide tables such as some Oracle Applications AOL tables, where select * repeats headers too often even with pagesize 100). Since we widened our sqlplus console window in the last step to, say, 188, we should make full use of it. But due to a problem with console window,note2 you should set linesize to 1 less than window size, e.g., 187. The only time you want a smaller linesize is when you DESCribe a table or view, so that column names and types are not too far apart in DESC output. (Interestingly, this DESCribe feature is not for DESCribing a PL/SQL package or procedure.)

But typing these set commands every time you start Sqlplus would be tedious, even with abbreviations such as set pages 100 lin 187. So add them to%oracle_home%\sqlplus\admin\glogin.sql, or current directory or %sqlpath%\login.sql. If one or both of them are already in there, change or delete them. Other useful settings are:note3

set long some_big_number serveroutput on arraysize 100 trimspool on tab off ...
column plan_plus_exp format a100
...

With the above window width and Sqlplus linesize setting, query column values for the same row need to be vertically aligned with the column headers (and dash lines), as in the case of select * from a_wide_table... Because Sqlplus uses tabs for fast display, some column headings or even values may not align very well with dash lines under the headings. Set tab off to correct the problem. If you really prefer to see one data row shown on one row, the preferred tool is Toad or any one under Toad Alternatives. But Sqlplus is not completely hopeless; you can set both window width and Sqlplus linesize to a very big number like 1000 to achieve the same, except that you may still need to manually set the width for varchar2(a big number) columns to a smaller size (e.g., col mycol for a80).

4. Environment variables

The following are commonly used environment variables that affect the behavior of Sqlplus, which can also be set in Windows registry. But if they're set in both places, environment variables take precedence. If you need to find the current value of a variable regardless where it's set, you can type@[%the_variable_name%] at SQL> prompt to see it outputs the literal string you typed (which means it's not set) or its value (when it's set); try @[%oracle_home%]and @[%nosuchvar%] to see what I mean. For a fairly complete list of the variables, see Radoslav Rusinov's article (see pp.12-7; translate with Google Translate).

LOCAL: Windows equivalent of UNIX TWO_TASK environment variable. With this set, sqlplus user/pass is translated to sqlplus user/pass@value_of_%LOCAL%.

NLS_DATE_FORMAT: I like to set it to yyyymmdd hh24:mi:ss so DATE type columns are displayed in my favorite format. The console command is: set nls_date_format=yyyymmdd hh24:mi:ss. (Yes, there is ONE space between dd and hh24 and it's NOT interpreted by set as two arguments!) Setting this environment variable is preferred over adding alter session set nls_date_format='yyyymmdd hh24:mi:ss' to [g]login.sql because you won't get the annoying "Session altered" feedback upon login, and as a bonus, if you use RMAN from this console window, timestamp in RMAN shows in this format too. So you may consider setting it in Control Panel as a system-wide variable. See also NLS_LANG below.

NLS_LANG: The primary purpose of this variable is as the name suggests. If your PC uses a code page other than 437 (check by chcp console command), you may wish to set this variable to english or american, unless you want feedback for the Sqlplus commands to be shown in your own language. Sometimes this variable is also changed in order to display foreign language text stored in the database, before running imp or exp (but not expdp or impdp) to avoid character set conversion; if the database you export from and the one you import into have different character sets, Oracle recommends you set NLS_LANG for your exp and imp environment to the same as the source, not target, database. Not widely known about this variable or registry key is the fact that if for some reason the registry is missing this key, setting NLS_DATE_FORMAT environment parameter alone won't let you see the desired DATE format when you select sysdate from dual; but since NLS_LANG is automatically set in registry during Oracle software installation, you're probably not aware of this issue. Equally obscure is the fact that if your Sqlplus starts in an NLS_LANG setting that differs in character set from that of the database you run queries in, sometimes Sqlplus widens the column in the output for string type columns, either for a query or for the Sqlplus print command to print the bind variable value. To see the difference, run select username from user_users in databases that use different charactersets after you set NLS_LANG to these two values,.al32utf8 and .we8iso8859p1 (note the leading dot). But using the setting .we8mswin1252 seems to avoid this problem.

SQLPATH: If somescript is in this directory, you can type @somescript at SQL> prompt to run it without specifying full path.

5. Tips

Many people are used to typing edit (or ed for short) at SQL> prompt to launch an editor. The problem is that it litters the file afiedt.buf wherever you launch Sqlplus. You can limit this litter to one single place with set editfile some_fixed_path\somefile.note4 Unless your SQL or PL/SQL commands are multi-line, you may enjoy better pressing UP arrow key to retrieve previous commands. This is one of the best features of the console version Sqlplus. The command line buffer size is only 50 by default and can be changed under Options tab in Properties window. Also, don't just use LEFT and RIGHT keys; press Home key (with NumLock off) to go to line beginning, Control-LEFT/RIGHT to move one word instead of one character at a time, and Esc to clean current line immediately. F7 is a little known trick in console; it shows all saved commands in your history buffer up to the history size (see below). Once you press F7, you can move UP/DOWN to the one you want, LEFT or RIGHT to select it on your command prompt (SQL>), or Enter to directly select and execute it, or Esc to cancel.

The beautiful window from F7

c:\ yong@testdb
SQL>
SQL>
SQL>
40: select sysdate from dual;
41: select * from v$lock where type!='MR';
42: desc v$session
43: select * from v$session where sid=123;
45: alter system kill session '123,2345';
46: select * from v$lock where type!='MR';



Since we enabled Quick Edit, you can double click on a word or select text to highlight it, right click or press Enter to copy (no message telling you it's copied), and right click again to paste (or in most applications such as Notepad, ^V to paste). Do not press ^C or ^V in this console window. ^V does nothing and ^C either exits Sqlplus or, if the query is still running inside the database, stops the query. It may take you a while to get used to the console window's copy and paste, and it's very confusing to have wrong text copied when you accidentally highlight some text (you can tell by the changed window title that begins with "Select"). This accidental highlight also "freezes" the screen; if you know your query should return rows now but the screen "hangs", make sure there's no text highlighted. (If there is, press any key such as Space to un-highlight.)

Another good feature is that you can set console window title with command such as title yong@testdb. At SQL> prompt, prepend with $ or host (or hos for short): host title yong@testdb. With a title for the console window, you can quickly spot it when it's minimized on the taskbar. If you don't set the title, our Sqlplus window opened by this Start-button shortcut will be "sqlplus - full_path_to_sqlplus". If you have to frequently set title because you often change connections (dropping a table in Prod while you thought you were in Dev is not pretty!), or because you often press ^C ending up at console command prompt, you can save a little effort by creating a short named sqlplus.exe, such as s.exe by copying sqlplus.exe to s.exe (in Windows Vista, a symbolic link will do). You may as well rename the Start-button shortcut to single letter "s". Then you can type s yong@testdb. The Sqlplus window will automatically bear the title "s - s yong@testdb". Doing that saves some typing and hopefully the title is short enough to show in the minimized tab on taskbar. Some people prefer to customize SQL> prompt to show DB name and/or username. You can follow this instruction (section "My Personal SQL Prompt"). Beginning with 10gsqlprompt adjusts _connect_identifier and _user dynamically. Obviously the console Window title or the label on the minimized tab won't automagically show the same string.

It's unfortunate that Oracle 11g no longer provides Windows Sqlplus (sqlplusw.exe). Although I don't recommend it for general use, it has some interesting features compared with the console version Sqlplus. Both Windows and console Sqlplus allow you to vertically highlight or copy text; vertically highlighting indented text makes reading an execution plan easier. And both Sqlplus output lines on terminal strictly based on time or input order, unlike in a Linux/UNIX terminal, where pasting multi-lines of SQL to it shows the SQLs mixed with query result in the middle instead of at the end.note5 On the downside, the command console doesn't support here document, so you can't pipe SQL or Sqlplus commands to a SQL session, as you would be able to do on Linux/UNIX.note6

Both Windows and console Sqlplus allow for string search (in console Sqlplus, go to Edit | Find). But the console Sqlplus can find strings from the entire buffer, as much as you can scroll back to, while the Windows Sqlplus only searches the visible screen.

Having said all these, the Windows version Sqlplus does have some unique features missing in the console version:

  • Windows Sqlplus never exits out of Sqlplus when you press Control-C (UNIX/Linux sqlplus doesn't either), while the console Sqlplus may. This is a very annoying problem and may be the only good reason sometimes I still use the Windows Sqlplus. Hopefully Bug 8890996, an enhancement request filed by me in 2009, will eventually get Oracle's attention.
  • The Windows Sqlplus has much more powerful special character display than the console version. Try select chr(49833) copyright from dual; in both to see what I mean. The weak capability of the console version could be dangerous in some cases; if the text column has two Carriage Return's, the Windows Sqlplus shows a rectangular dot, which serves as a warning something is here, but the console version silently "erases" the first part of the text. Try select 'x'||chr(13)||'y'||chr(13)||'z' from dual;. The behavior doesn't change with different NLS_LANG settings.note7

6. Useful link

William Robertson's Setting up SQL*Plus on Windows is very user-friendly.

_________________

[note1] Some people call the command console a DOS window. But the correct way to say is that sqlplus.exe is a Win32 Console application, and sqlplusw.exe a Win32 GUI app. (Thanks to Dennis Yurichev's correction)

[note2] See details here. The problem does not exist on a UNIX/Linux terminal.

[note3] Set long big_number so you can see the definition of a complicated trigger or view, or text in any long or clob column. Serveroutput on is for dbms_output.put_line (but do NOT set it to on if you need to call dbms_xplan.display_cursor in 10g to show the plan for the last executed SQL), or if you simply don't like the little overhead of that one extra consistent get. A bigger than default 15 arraysize (or array for short) is to save on consistent gets; the default 15 is rarely adequate (Perhaps it increases a little sqlplus.exe process memory and server side PGA). Trimspool is to remove trailing space characters in the spool file padded to linesize so the file is smaller and lines don't "mysteriously" wrap.
Before 10g, column plan_plus_exp needs to be larger so your explain plan output doesn't wrap lines too early. It's interesting that plan_plus_exp can only be set to linesize-19 at maximum unless you reduce object_node_plus_exp; beyond that, explain plan output lines wrap. So if linesize is say 145, you need col plan_plus_exp for a126, not a127. Beginning with 10g client, you don't need to worry about this column setting.

[note4] If you set editfile nul:, you get "Incorrect function" message when you edit and the default editor is Notepad, as if you typed notepad nul: at command prompt. So this is not an option. (On Linux/UNIX, if you set editfile /dev/null, you see an empty vi editor and you get "/dev/null" is not a filemessage when you edit, as if you typed vi /dev/null at shell level.)

[note5] Private email with Don Libes, the author of the Expect programming language, confirms that there's no workaround for this feature of UNIX terminals, unless the program (sqlplus here) has custom code to avoid this "premature" echoing. But some shells behave better than others. For instance, in bash you would paste a lot of lines at once on a fairly fast connection to the terminal to see jumbled lines.

[note6] Somebody wrote a very clever script to mimic a here document in the command console (originally posted here):

@echo off
FIND "/*%none% some_label" <%0 |sqlplus username/password
GOTO end
: ----------- embedded SQL-------------------------
/* some_label */ select * from dba_free_space where rownum = 1;
/* some_label */ rem select tablespace_name from dba_tablespaces;
: ----------- end of embedded SQL-------------------------
:end

[note7] This is actually a problem with the Windows console, not Sqlplus itself. UNIX/Linux terminal suffers from the same problem. See my posting to Oracle-L.

[2011-08 Update]
In Windows 7, the path is
C:\Users\user\AppData\Roaming\Microsoft\Windows\Start Menu\Programs
You need to manually type AppData in the path since it's hidden.


:
Posted by Elick
2011. 3. 11. 11:47

함수 비교 (substr, substring) Work/Etc2011. 3. 11. 11:47

처리해야 될 작업발생 :  mdb(ms access)로 되어 있는 Query들을 Oracle로 이관.

LEFT, RIGHT 함수에 대해서 Oracle에서 지원을 하지 않는다!!


http://www.techonthenet.com/oracle/functions/substr.php


위 링크에서 확인할 수 있듯이 substr 함수는 

    substr( string, start_position, [ length ] )

위와 같이 사용하면 되는데... 이 때 start_position 에 음수/양수 사용으로 방향이 결정.

양수를 사용하면 처음부터 시작해서 길이만큼 세고, 음수를 사용하면 뒤부터 시작해서 거꾸로 길이만큼 센다.

이 기능이면 충분히 LEFT, RIGHT 를 대체가능!!



[DB마다 비교]


SQL Server 질의 : 결과

SELECT SUBSTRING('123456789', 0, 3) : 12

SELECT SUBSTRING('123456789', -3, 5) : 1


Oracle 질의 : 결과

SELECT SUBSTR('123456789', 0, 3) : 123 -- Oracle은 start_position 1과 0을 같은 것으로 간주합니다.

SELECT SUBSTR('123456789', -3, 5) : 789 -- 뒤에서 3번째 글자 부터 5글자 이므로...


PostgreSQL 질의 : 결과

SELECT SUBSTRING('123456789', 0, 3) : 12

SELECT SUBSTRING('123456789', -3, 5) : 1


:
Posted by Elick
cmd 에서 service를 시작 / 중지 등을 하고 싶은 경우가 있다.

서비스 시작 : net start [서비스 이름]
서비스 중지 : net stop [서비스 이름]

별거 아니지만 찾으려니까 없었다.. ㅠㅠ

File bacup 시 xcopy 를 사용하는데 주로 사용하는 option 은 아래와 같다.
/D : 지정된 날짜 이후에 바뀐 파일만 복사합니다. 날짜가 지정되지 않으면, 대상 파일보다 새로운 원본 파일만 복사합니다.
/S : 비어 있지 않은 디렉터리와 하위 디렉터리를 복사합니다.
/F : 복사하는 동안 원본과 대상 파일의 전체 경로 를 표시합니다.
/Y : 이미 있는 대상 파일을 덮어쓸지를 확인하기 위해 묻는 것을 금합니다.
:
Posted by Elick