새로운 시스템 decomposition · web viewtablename : proxy table로 생성할local table....

161
ADMIN -1 (device,lock,memory,charset 목목 ) 1.disk init 2.disk mirror 3.device move 4.login/user 5.cis 6.lock 7.lock promotion 8.table lock schemes 9.deadlock 10.memory 11.ASE basic thread 12.목목 ASE 목 목목목 목목 13.ASE configuration 14.charset ADMIN -2 (3gl,open client 목목 ) 1.esqlc 2.win/nt 3.목목목목 (db,dbo,table 목) 4.misc 5.password 목목 6.ASE 목목목목 7.DBA 목목목 목 ADMIN -3 (database,dump/load,log,dbcc 목목 ) 1.create/alter database

Upload: others

Post on 09-May-2020

9 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

목 차

ADMIN -1 (device,lock,memory,charset 관련 ) 1.disk init 2.disk mirror 3.device move 4.login/user 5.cis 6.lock 7.lock promotion 8.table lock schemes 9.deadlock 10.memory 11.ASE basic thread 12.현재 ASE 는 무엇을 하나 13.ASE configuration 14.charset

ADMIN -2 (3gl,open client 관련 )

1.esqlc 2.win/nt 3.이름변경 (db,dbo,table 명) 4.misc 5.password 관련 6.ASE 관리기본 7.DBA 이것은 꼭 ADMIN -3 (database,dump/load,log,dbcc 관련 )

1.create/alter database 2.dump database 3.load database

Page 2: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

4.db option 5.logsegment 6.log suspend 7.log 8.system table 9.tempdb 10.dbcc 11.table partition UTILITY 1.bcp 2.defncopy 3.dscp 4.optdiag 5.reorg 6.isql 7.buildmaster

SQL 1.trigger 2.stored procedure 3.identity 4.chained Vs. unchained Mode 5.datetime 6.escape & wildcard 7.set 8.isolation level 9.key 10.sql 문장 11.dynamic sql

2

Page 3: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

ADMIN -1 (device,lock,memory,charset 관련 )

1.Disk init1.Disk init Syntax raw partition Vs file system ? raw partition 을 사용하는 경우 주의점은? device 정보를 보는 방법은? vdevno 를 찾는 방법은? Device 허용되는 최대 size 는? Device 가 어느 Database 에 속해있는지 볼 수 있는가? Device 가 어느 정도 사용되는지 볼 수 있는가? ERROR # 5123 발생하는 경우는?

Syntax Syntax Raw Partition disk 또는 O/S File system 을 사용할 수 있는 영역으로 확보하는 작업이다physical disk(or operating system file)와 database device name 를 mapping 시킨다

disk init name = 'device_name', physname = 'physical_name', vdevno = virtual_device_number, size = number_of_pages … [,contiguous] /* Open VMS only */name : logical name, ASE 에서 사용되는 device 명physname : 실제로 사용되는 OS 의 file 명 또는 raw partition 명 해당 디렉토리에 대한 sybase login id 의 쓰기 권한이 부여되어야 한다 파일 시스템을 사용할 경우 동일 이름의 파일이 존재하면 안 된다vdevno : 1 ~ 255 size : page 수 (1 page = 2k 이다)

예) 'user_data'란 logical device 이름으로 100MB(51200 Page) 영역 확보1>disk init name = 'user_data',2>physname = 'home/sybase/data/data1.dat',3>vdevno = 2,4>size = 512005>go

raw partition Vs file system ?raw partition Vs file system ? sybase 는 안정적 측면에서 Raw Partition 사용을 권장하고 있다 1) Unix file system 을 사용한다면 system crash 가 발생한 경우 recovery 를 보장하지 못한다 Unix buffering 은 실제 commit 된 정보를 disk 에 직접 write 하지 않고 지연되므로 그 순간에 media failure 니 O/S crash 가 발생한다면 그 데이타는 분실할 것이다 2) Raw Partition 은 Disk buffering(Disk 에 데이타를 직접 write)을 사용하지 않으므로 Unix File System 보다는 데이타 분실을 크게 줄일 수 있고, 사용자가 쉽게 rm 으로 실수 하는 경우가 없다. 그러나 관리상 문제는 발생할 수 있다. 3)raw partition 이란 UNIX system 에서 mount 되지 않은 disk 부분이다

3

Page 4: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

raw partition raw partition 을을 사용하는사용하는 경우경우 주의점은주의점은?? Cylider 0 는 사용되지 않게 한다 만약 cylinder 0 를 ASE 데이타 영역으로 할당했다면 partition 정보를 갖고 있는 'disk label'에 overwrite 할 것이고 O/S 가 Re-startup 되면 Unix 는 Partition 정보가 없는 것을 확인하고 ASE 가 사용하고 있는 영역에 partition 정보를 rewriting 하면 DB 는 corrupt 되고 더 이상 DB 를 사용할 수 없다

ASE 의 unix login id 가 raw partition disk 에 read/write 가 가능한 owner 이어야 한다

raw partition 을 사용할 경우 그 정보를 늘 관리하는 것이 좋다

devicedevice 정보를정보를 보는보는 방법은방법은?? sp_helpdevice : Device 에 대한 유용한 정보를 볼 수 있다

vdevnovdevno 를를 찾는찾는 방법은방법은??

STEP 1) 현재 사용되는 vdevno 를 알아본다1> use master2> go1> select name, low / power(2,24) from sysdevices2> go name vdevno ------------------------------ ----------- ahn_dev 11 ahn_dev2 13 for_data 9 for_log 8 master 0 mulli 7 sysprocsdev 1 temp_dev 21

STEP 2) vdevno 로 사용할 수 있는 최대값을 알아본다1> sp_configure 'number of devices'2> goParameter Name Default Memory Used Config Value Run Value ---------------------------------------------------------------------- number of devices 10 #13 30 30

STEP 3) STEP 2)의 Run Value 보다 1 적은 값을 최대로 사용하며, STEP 1)에서 사용하지 않는 것을 찾는다. 만약 없으면 STEP 4)를 수행한다

STEP 4) 사용가능한 vdevno 를 늘려준다1> sp_configure 'number of devices', 502> go1> shutdown2> go

DeviceDevice 로로 허용되는허용되는 최대최대 sizesize 는는??32 giga

4

Page 5: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

DeviceDevice 가가 어느어느 DatabaseDatabase 에에 속해있는지속해있는지 볼볼 수수 있는가있는가??1> select d.name 'device 명', db_name(u.dbid) 'db 명', u.size / 512 'Usage_Meg'2> from sysdevices d, sysusages u3> where u.vstart between d.low and d.high4> order by d.name5> go device 명 db 명 Usage_Mega ------------------------------ ------------------------------ ----------- master master 6 master master 14 master tempdb 2 master model 2 master pubs2 3 master sybsystemdb 2 phd_dev phd 10 phd_dev phd 10 phd_log phd 20 she_dev she 10 she_log she 10

DeviceDevice 가가 어느어느 정도정도 사용되는지사용되는지 볼볼 수수 있는가있는가??1> select 'Database device name' = name2> , 'In use by database' = sum (size / 512)3> , 'Space initialized' = (high - low + 1)/ 5124> from sysdevices,sysusages5> where vstart between low and high6> and cntrltype = 07> group by name8> go Database device name In use by database Space initialized ------------------------------ ------------------ ----------------- master 13 30 sysprocsdev 60 60 test_dev 50 50

(3 rows affected)

Error #5123 Error #5123 발생하는발생하는 경우는경우는?? 만들려는 device 의 physname 이 이미 존재하는 경우이다. rm 으로 제거해 주어야 한다

1> disk init name = 'testdev',size = 512, physname = '/tmp/testdev', vdevno=62> go1> sp_dropdevice testdev2> goDevice dropped.(return status = 0)

sp_dropdevice 한 뒤, unix 인 경우 rm 으로 os 상의 제거명령을 주어야 한다

1> disk init name = 'testdev',size=512,physname = '/tmp/testdev',vdevno=92> goMsg 5123, Level 16, State 1:Server 'ASE12A', Line 1:DISK INIT encountered an error while attempting to open/create the physicalfile. Please consult the SQL Server error log (in the SQL Server bootdirectory) for more details.

5

Page 6: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

2.Disk mirror2.Disk mirror Syntax Mirroring 하는 이유? Mirroring 하는 대상은? Master device 를 mirroring 한 경우, RUN_SERVER FILE 에 해줘야 할 옵션은? Mirroring 을 다시 시작하고 싶은 경우는? Mirroring 을 영원히 하지 않고 경우는? Mirroring 을 잠시 사용하지 못 하는 경우는? Mirroring 상태를 확인하는 방법? Mirroring solution 으로 Disk / OS / ASE 중 어떤 방법을 선택할 것인가? Msg 5155 가 발생하는 경우는? errorlog 에서 secondary 로 넘어간 것이 어떻게 나타나는가? secondary 로 넘어간 다음 어떻게 해야 하나?

SyntaxSyntax Database Device 의 내용을 ASE 기능으로 복제할 수 있는 기능이다양쪽 디스크에 동시에 Write 한다. Read 는 항상 Primary Side 로부터 한다

disk mirrorname = 'device_name',mirror = 'physical_name'[,writes = {serial | noserial}]

device_name : 이미 존재하는 mirror 대상 device 를 명시해야 한다mirror : 실제 mirror 될 physical file 을 명시해야 한다

1> disk mirror name = 'mirror_dev',mirror='/tmp/mirror_dev_2'2> goCreating the physical file for the mirror...Starting Dynamic Mirroring of 1024 pages for logical device 'mirror_dev'.The remaining 1024 pages are currently unallocated and will be mirrored as theyare allocated.

Mirroring Mirroring 하는하는 이유는이유는?? 디스크 장해로 인한 Downtime 시간을 최소로 할 수 있다 디스크 관련 장애로부터 확실한 복구가 보장된다

TradeOff 1) 추가적인 S/W 구매는 필요하지 않다 2) 자원(Disk Storage)이 추가적으로 사용된다 3) 이중으로 Write 하기 때문에 약간 속도가 떨어진다

Mirroring Mirroring 하는하는 대상은대상은?? Master Device,Log Device,Active Device 등 중요한 Device 에 대하여 Mirring 하는 것이 좋다

Master deviceMaster device 를를 mirroringmirroring 한한 경우경우, RUN_SERVER FILE, RUN_SERVER FILE 에에 해줘야할해줘야할 옵션옵션 RUNSERVER 파일에 Mirror 할 Physical Name 을 추가하여야 한다예) dataserver –ddevicename … [-rmastermirror_devicename]

6

Page 7: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

MirroringMirroring 을을 다시다시 시작하고시작하고 싶은싶은 경우는경우는?? disk remirror 를 한다disk remirror name = 'device_name'

Logging00:00000:00001:2000/11/23 09:11:55.89 kernel mirror for virtual device 35 started using asynchronous I/O

MirroringMirroring 을을 영원히영원히 하지하지 않는않는 경우는경우는?? disk unmirror 를 하고 mode = remove 한다1>disk unmirror 2>name = 'device_name', 3>side = primary, 4>mode = remove5>go

Logging00:00000:00001:2000/11/23 09:42:45.81 kernel Closing the secondary device for virtual device Test_dev

MirroringMirroring 을을 잠시잠시 사용하지사용하지 못하는못하는 경우는경우는?? disk unmirror 를 하고 mode = retain 한다1>disk unmirror 2>name = 'device_name', 3>side = primary, 4>mode = retain5>go

MirroringMirroring 상태를상태를 확인하는확인하는 방법방법?? sp_helpdevice 로 Mirroring 정보를 얻을 수 있다

1> sp_helpdevice Test_dev2> go device_name status --------------------------------------------------------------------------------------------------------------------- Test_dev special, MIRROR ENABLED, mirror = '/ase/ase12/devices/testmirror.dat',serial writes, dsync on, reads mirrored, physical disk, 100.00 MB

Mirroring solutionMirroring solution 으로으로 Disk / OS / ASE Disk / OS / ASE 중중 어떤어떤 방법을방법을 선택할선택할 것인가것인가?? 일반적으로 Disk , OS, ASE 순으로 선택한다

ASE 에서 Mirror 를 하는 경우는 2 번 write 해야 하는 것을 dataserver 에서 처리해서 느려질 수 있다

Msg 5155 Msg 5155 가가 발생하는발생하는 경우는경우는?? sp_configure 'disable disk mirroring',0 한 뒤 restart 한다

errorlogerrorlog 에서에서 secondarysecondary 로로 넘어간넘어간 것이것이 어떻게어떻게 나타나는가나타나는가?? 다음과 같이 나타난다00:00000:00005:2000/12/07 09:17:36.84 kernel Closing the primary device for virtual device devFORmirror00:00000:00005:2000/12/07 09:17:36.84 kernel Continuing i/o on the secondary device /tmp/devFORmirror_s

7

Page 8: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

secondarysecondary 로로 넘어간넘어간 다음다음 어떻게어떻게 해야하나해야하나??방법 1) 양쪽을 똑같이 맞춰주는 작업을 하려면, remirror 를 한다1> disk remirror name='devFORmirror'2> go00:00000:00009:2000/12/07 09:24:07.70 kernel mirror for virtual device 6 startOStarting Dynamic Mirroring of 1024 pages for logical device 'devFORmirror'. 512 pages mirrored... 1024 pages mirrored...

방법 2) primary 쪽을 제거하려면 다음 작업을 한다1> disk unmirror name='devFORmirror',side=primary,mode=remove2> go

3.device move3.device move 방법 1) dump & load 방법 2) mirror 를 이용한다 방법 3) physical 한 device 를 옮긴후, sysdevices.phyname 을 수정한다

방법방법 1) dump & load1) dump & loadSTEP 1) 옮기고자 하는 device 를 사용하는 database 모두를 dump 로 backup 받는다STEP 2) sp_dropdevice 와 drop database 로 device 와 database 를 삭제한다STEP 3) disk init 으로 새로운 위치에 device 를 만든다STEP 4) create database … for load 로 database 를 새로이 만든다STEP 5) load database 로 dump 받은 것을 load 한다

방법방법 2) mirror2) mirror 를를 이용한다이용한다STEP 1) disk mirror 로 옮기려는 device 에 mirror 를 시작한다1> sp_helpdevice devFORmirror2> go device_name physical_name description status cntrltype device_number low high ------------------------------ ---------------------------------------------- ----------------------------------------------------------------------- ------ --------- ------------- ----------------------------------------------------------------------- ----------------------------------------------------------------------- devFORmirror /tmp/devFORmirror special, MIRROR ENABLED, mirror = '/tmp/devFORmirror_s', serial writes 17122 0 6 6

STEP 2) disk unmirror side=primary,mode=remove 로 옮기려는 device 의 mirror 를 제거한다 1> disk unmirror name = 'devFORmirror', side='primary',mode=remove2> go00:00000:00009:2000/12/07 14:14:54.40 kernel Closing the primary device for vir00:00000:00009:2000/12/07 14:14:54.40 kernel The new primary device is now /tms1> sp_helpdevice devFORmirror2> go device_name physical_name description

8

Page 9: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

status cntrltype device_number low high ------------------------------ ---------------------------------------------- ----------------------------------------------------------------------- ------ --------- ------------- ----------------------------------------------------------------------- ----------------------------------------------------------------------- devFORmirror /tmp/devFORmirror_s special, MIRROR DISABLED, mirror = '', nonserial writes, dsync on, phy 16386 0 6 6

방법방법 3) physical3) physical 한한 devicedevice 를를 옮긴후옮긴후, sysdevices.phyname, sysdevices.phyname 을을 수정한다수정한다STEP 0) database backup 은 필수적이다

STEP 1) ASE 를 shutdown 한다1> disk init name = 'devFORmove',physname = '/tmp/devFORmove',size=1025,2> vdevno=103> go1> create database dbFORmove on devFORmove = 22> goCREATE DATABASE: allocating 1024 pages on disk 'devFORmove'1> shutdown2> go

STEP 2) device 의 physical file 을 옮긴다 (/tmp/devFORmove 를 /tmp/TMP/devFORmove 로)[digital:/home/ase12/ASE-12_0/install 7 ] cd /tmp[digital:/tmp 8 ] mkdir TMP[digital:/tmp 9 ] mv devFORmove TMP[digital:/tmp 10 ] ls TMPdevFORmove

STEP 3) ASE 를 startserver 한다[digital:/home/ase12/ASE-12_0/install 13 ] startserver -f RUN_ASE12Aerrorlog 에 다음 내용이 나오면서, device 와 db 둘다 사용할 수 없다고 나온다00:00000:00001:2000/12/07 13:46:06.01 kernel udstartio: vdn 10 has not been sep00:00000:00001:2000/12/07 13:46:06.03 server Error: 840, Severity: 17, State: 100:00000:00001:2000/12/07 13:46:06.03 server Device 'devFORmove' (with physica.00:00000:00001:2000/12/07 13:46:06.08 server Unable to proceed with the recove.00:00000:00001:2000/12/07 13:46:06.22 server

1> sp_helpdevice devFORmove2> go ----------------------------------------------------------------------- ----------------------------------------------------------------------- 167772160 167773184 16386 0 devFORmove /tmp/devFORmove NULL

STEP 4) sysdevices.physname 의 내용을 새로이 옮기는 device file 의 위치로 바꾼다[digital:/home/ase12/ASE-12_0/install 22 ] isql -Usa -Psybase1> begin tran2> go1> update sysdevices set phyname = '/tmp/TMP/devFORmove'2> where low / power (2,24) = 103> go(1 row affected)1> commit tran2> go

9

Page 10: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

STEP 5) shutdown 한 뒤, 다시 start 하면 device 는 제대로 활성화된 것을 확인할 수 있다00:00000:00001:2000/12/07 13:57:18.15 server Activating disk 'devFORmove'.00:00000:00001:2000/12/07 13:57:18.15 kernel Initializing virtual device 10, '.00:00000:00001:2000/12/07 13:57:18.15 kernel Virtual device 10 started using s.

그러나, 아직도 db 는 제대로 사용할 수 없는 상황이다1> use dbFORmove2> goMsg 926, Level 14, State 1:Server 'ASE12A', Line 1:Database 'dbFORmove' cannot be opened. An earlier attempt at recovery marked it'suspect'. Check the SQL Server errorlog for information as to the cause.

STEP 6) 아래와 같이 조치한다1> use master2> go1> begin tran2> go1> update sysdatabases set status = 0 where dbid = db_id("dbFORmove")2> go(1 row affected)1> commit tran2> go1> shutdown2> go

다시 start 하면 db 도 정상적으로 된다00:00000:00001:2000/12/07 13:59:13.74 server Recovering database 'dbFORmove'.00:00000:00001:2000/12/07 13:59:13.94 server Checking external objects.00:00000:00001:2000/12/07 13:59:13.97 server The transaction log in the databa.00:00000:00001:2000/12/07 13:59:14.06 server Database 'dbFORmove' is now onlin.

4.LOGIN / USER4.LOGIN / USER 원하는 DB 에 login 하여 원하는 작업을 하려면?

10

Page 11: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

몇가지 작업을 할 수 있는 권한을 login 에게 줄 수 있는가? group 이란? 특이한 group : public 특이한 user : guest sybase 에서 alias 란? ASE 연결시, 해당 DB 에 직접들어가게 하는 법은?

이미 정의된 role 의 종류와 업무들 원하는원하는 DBDB 에에 login login 하여하여 원하는원하는 작업을작업을 하려면하려면?? unix login -> ASE (login name) -> DB (user name) -> Object (실행권한) 과정을 거친다

ASE 에 login 할때는, isql -Usa -P 를 사용했다이때 sa 가 바로 login 명이 된다[syb-sun:/ase/ase12/ASE-12_0/install 11 ] isql -Usa -Psybtech1

어떤 login name 을 사용하는지 알아본다1> select suser_id(), suser_name() 2> go ------ ------------------------------ 1 sa

현재 db 에서 어떤 user name 을 사용하는지 알아본다1> select user_id(), user_name()2> go

------ ------------------------------ 1 dbo

위의 내용에서처럼, 각 login 명과 user 명은 내부적으로 login id 와 user id 를 갖습니다한 login 명이 어떤 db 에 들어갈때는, 그 db 에 해당하는 user 명으로 해서 들어간다

예) login_name 이라는 login 을 등록한다1> use master2> go1> sp_addlogin 'login_name','login_password',pubs22> goPassword correctly set.Account unlocked.New login created.(return status = 0)

login_name 을 pubs2 db 에서는 pubs2_user 라는 user 명으로 등록한다1> use pubs22> go1> sp_adduser login_name,pubs2_user2> goNew user added.

11

Page 12: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

login_name 을 sybsystemprocs db 에서는 sybsystemprocs_user 라는 user 명으로 등록한다1> use sybsystemprocs2> go1> sp_adduser login_name,sybsystemprocs_user2> goNew user added.

확인한다[syb-sun:/ase/ase12/ASE-12_0/install 12 ] isql -Ulogin_name -Plogin_password1> select suser_name(),suser_id()2> go ------------------------------ ------ login_name 5(1 row affected)1> use pubs22> go1> select suser_name(),suser_id(),user_name(),user_id()2> go ------------------------------ ------ ------------------------------ ------ login_name 5 pubs2_user 41> use sybsystemprocs2> go1> select suser_name(),suser_id(),user_name(),user_id()2> go ------------------------------ ------ ------------------------------ ------ login_name 5 sybsystemprocs_user 3

sp_addlogin : login 등록하는 proceduresp_addlogin loginame, passwd [, defdb] [, deflanguage [, fullname]]]예) sp_addlogin "maryd", "100cents" , pubs2

1)oginame : 새로운 user 의 login name. Adaptive Server 내에서 unique 해야 하며, login process 와 server administration 업무를 단순화하기 위해서 OS 상에서 사용하는 user name 을 사용하는 것이 바람직하다 2) passwd 는 6 자 이상이어야 한다 3) defdb : login 시(start session)에 default 로 설정되는 database.이다 기본적으 master 로 되어 있지만,masster database 가 아닌 다른 database 로 설정하는 것이 좋다

sp_adduser : database 에 Adaptive Server User 를 추가하는 프로시져sp_adduser loginame [, name_in_db [, grpname]]예) 1> sp_addlogin ahneunhee,ahneunhee123,pubs2 2> go

1) loginame : existing user 의 login name 2) name_in_db : database 내에서 식별될 수 있는 이름으로 login name 과는 다른 의미의 이름. Adaptive Server 내에 동일한 이름의 사용자가 여럿 있을 때, 만약 서로 다른 database 를 사용할 경우 user preference 를 위해 지정할 수도 있다. 만약 지정하지 않으면, login name 이 default 로 사용된다 3) grpname : database 내의 group name, 만약 지정되지 않으면, default 로 ‘public’ 그룹으로 지정된다

특정작업을특정작업을 할할 수수 있는있는 권한을권한을 useruser 에게에게 줄줄 수수 있는가있는가??

12

Page 13: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

grant 로 줄 수 있습니다1> grant create table to pubs2_user2> go

여러 개의 특정 작업을 할 수 있는 권한을 묶은 것을 role 로 정의할 수 있다1> use master2> go1> create role 'DOeverything'2> go1> use pubs22> go1> grant all on publishers to DOeverything2> go1> grant all on authors to DOeverything2> go1> use master2> go1> grant create database to DOeverything2> go

group group 이란이란?? db 내에서 user 를 grouping 한 것이다1> sp_adduser login_name,pubs2_user,Group_A2> goNew user added.(return status = 0)1> sp_helpuser2> go Users_name ID_in_db Group_name Login_name ----------------- -------- ----------------- --------------------------------------------------- dbo 1 public sa guest 2 public NULL pubs2_user 4 Group_A login_name user01 3 public user01(return status = 0)

특이한특이한 group : publicgroup : public 모든 user 는 public 이라는 group 에 default 로 들어가 있다만약 특정 user 만이 어떤 권한을 갖게 하고 싶다면, revoke [어떤 권한] from public 을 수행한뒤에 grant [어떤 권한] to [특정 user] 를 수행한다1> sp_adduser login_name,pubs2_user,Group_A2> goNew user added.(return status = 0)1> sp_helpuser2> go Users_name ID_in_db Group_name Login_name ----------------- -------- ----------------- --------------------------------------------------------dbo 1 public sa guest 2 public NULL pubs2_user 4 Group_A login_name user01 3 public user01(return status = 0)1> sp_addgroup Group_B2> goNew group added.(return status = 0)1> revoke all on publishers from public2> go

13

Page 14: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

Some or all of the specified privileges were not revoked because, they were notgranted, or they were granted by some other user.1> exit[syb-sun:/ase/ase12/ASE-12_0/install 16 ] isql -Ulogin_name -Plogin_password1> use pubs22> go1> select * from publishers2> goMsg 10330, Level 14, State 1:Line 1:SELECT permission denied on object publishers, database pubs2, owner dbo

특이한특이한 user : dbo,guestuser : dbo,guest dbo 1) 모든 db 는 dbo 라는 user 를 갖고 있다 2) 이것은 database 의 owner 라는 뜻이다 3) sa_role 을 갖는 모든 login 은 'use database 명' 으로 db 에 접근해서 user_name()을 보면 dbo 입니다. 즉 모든 db 에서 dbo 로 작업합니다

guestdb 에 guest 라는 user 가 있다면, 모든 사람에게 그 db 에 접근을 허용한다login 명이 그 db 에 특정 user 로 등록되지않은 경우에, guest 라는 user 명으로 접근하기 때문이다만약 특정 login 명만 db 에 접근을 하게 하고 싶다면, sp_dropuser guest 부터 한 뒤에 sp_adduser 를 수행한다

sybasesybase 에서에서 aliasalias 란란??dbname.owner.tablename 을 간단하게 alias 로 하고 싶어하는 분들이 있는데 ASE 는 그런 기능은 없다 ASE 에서의 alias 는 여러개의 login 명을 존재하는 db 의 user 명으로 연결해주는 기능이다

login 명 중 victoria 가 있다. database 의 user 명 중 albert 가 있다예) 해당 db 에서 다음과 같이 해 주면, 새로운 user 명이 아닌 기존의 user 명을사용하게 할 수 있다sp_addalias victoria, albert

ASEASE 연결시연결시, , 해당해당 DBDB 에에 직접들어가게직접들어가게 하는하는 법은법은??sp_modifylogin - Modifies values for a login, including default databa

language, role activation, password options, full name

sp_modifylogin loginame, {"defdb | deflanguage | fullname | add defa

| drop default role | min passwd length | passwd expiration |

max failed_logins"}, value

14

Page 15: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

이미이미 정의된정의된 rolerole 의의 종류와종류와 업무들업무들 sa_role, sso_role, oper_role, navigator_role, replication_role, sybase_ts_role 이 있다role 종료 작업내용

Sa_role (시스템 관리자) ASE 모듈설치

DEVICE,LOGIN,SERVER 관리

memory,connection 같은 configuration 관리

create database 권한부여

모든 db 의 owner 로 역할

sso_role(보안 관리자) login 추가,password 관리,audit 시스템 구성

oper_role dump database/ transaction

load database/transaction

navigator_role navigator server 관리

replication_role replication server 관리

sybase_ts_role dbcc 명령 중 dbcc rebuild_log 등은 sybase_ts_role 을 요구한다,

5.CIS (component Integration Service)5.CIS (component Integration Service)

CIS Setup 어떻게 하나? Proxy Table 생성을 어떻게 하나? CIS 관련 dbcc trace 종류는? Msg 11206 발생하면? Msg 11216 발생하면? performance tunning

15

Page 16: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

CIS Setup CIS Setup 어떻게어떻게 하나하나??다음과 같은 순서로 한다

STEP 1) CIS configuration Parameter 를 수정한다1> sp_configure 'enable cis', 11> shutdown2> gostartserver -f RUN_[Server 명]

STEP 2)Local Server 정의1> sp_addserver Local_Server_Name, local 2>go1> shutdown2> gostartserver -f RUN_[Server 명]1> select @@servername -- 확인2> go

STEP 3)interfaces file 수정Remote Server 의 Server Name 과 IP-Address, Port Number 을 추가한다isql 로 -S 을 사용하여 확인한다isql -Uuser -Ppasswd -Sremote_server_name

STEP 4) Adaptive Server 안에 Remote Server 정의

1> sp_addserver ase12,sql_server,ase122> goAdding server 'ase12', physical name 'ase12'Server added.sp_addserver gateway, sql_server, gateway

STEP 5) sp_helpserver 로 확인한다

STEP 6) 서로 교류할 수 있는 Login 설정server : remote server nameloginname : ASE login nameexternname : remote server loginexternpassword : remote server login password1> sp_addexternlogin ase12,sa,sa,sybtech12> goUser 'sa' will be known as 'sa' in remote server 'ase12'.(return status = 0)sp_addexternlogin server, loginname, externname [, externpassword]

STEP 7) Passthrough Mode 로 접속한다접속 : connect to servername끊음 : disc[onnect]

Passthrough 가 설정되면 Remote Server 의 토착의 SQL Syntax 을 사용해야 한다Passthrough 를 사용하기 전에 User 에게 connect to 명령어를 쓸 수 있도록 Permission 을 주어야 한다

16

Page 17: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

Proxy TableProxy Table 생성을생성을 어떻게어떻게 하나하나?? Manual 로 생성

STEP 1)Remote Object 의 저장위치와 이름 정의1> sp_addobjectdef proxy1, 'ASE1.pubs2.dbo.publishers'2> gosp_addobjectdef tablename, 'objectdef' [,'objecttype'] tablename : Proxy table 로 생성할 local table objectdef : 외부 Object 의 저장위치 objecttype : view, table, rpc

STEP 2) Proxy Table 에 Remote Object Map1> create existing table proxy1 (col1 decimal,col2 text)2> gocreate existing table table_name (column_list) table_name : sp_addobjectdef 에서 생성된 table name

STEP 3) update statistics 실행 update statistics table_name 정의된 Index 에서 분포(distribution)의 Key 값에 대한 정보를 Update 한다 CIS 는 통계정보를 이용한다

Sybase Central 을 이용하여 생성

STEP 1) Proxy Table 을 추가할 Database 선택STEP 2) Proxy Table Container 를 클릭STEP 3) Add proxy table 을 더블클릭. Create a Proxy Table wizard 가 시작된다STEP 4) Proxy table 의 기초가 되는 Remote Object 의 종류 선택STEP 5) Remote Server 및 Database 선택STEP 6) 원하는 Object 을 선택하여 Table 내용 변경 후 저장한다

cis cis 관련관련 dbcc trace dbcc trace 종류는종류는??문제가 생길 경우, 다음을 setting 하고 결과를 본다11201 client connection 을 기록한다11202 client language,cursor,dynamic prepare,

dynamic execute-immediate text 을 기록한다11203 client rpc event 를 기록한다11204 client 에게 가는 모든 message 를 기록한다11205 remote server 간의 모든 대화를 기록한다11207 text,image 처리사항을 모두 기록한다

Msg 112Msg 1121166 발생하면발생하면??Msg 11216, Level 16, State 1:Server 'syalder', Procedure 'dp_insrt_init_price_book_test', Line 25:Internal Ct-Lib/Cs-Lib error 4002: 'Login failed.

접속권한과 관련된 문제이므로 public 에게 권한을 준다

17

Page 18: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

grant connect to public

Msg 11206Msg 11206 발생하면발생하면??/App/sybase/install> isql -Usa -P1> connect to SYB_SAIS2> goMsg 11216, Level 16, State 1:Line 1:Internal Ct-Lib/Cs-Lib error 84083972: 'ct_connect(): network packetlayer:internal net library error: Net-Lib protocol driver call to connect twoendpoints failed'.Msg 11206, Level 16, State 1:Line 1:Unable to connect to server 'SYB_SAIS'.1> exit 다음 값들을 sp_configure 로 조정한다 1) "number of remote connections" 2) "number of remote logins" 3) "number of user connections" 4) "cis connect timeout"

Performance tunningPerformance tunning local table 과 remote table 간의 join 을 삼가 한다 update statistics 를 수행한다

6.LOCK 6.LOCK lock 이 생긴다? intent lock 이 무엇인가? (lock 종류와 대상) lock 발생과 해제는 언제인가? lock 탐지 (sp_who,sp_lock 통한)하는 방법은? lock contention 줄이는 방법은?

18

Page 19: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

lock 기다리는 시간을 무한정에서 일정시간으로 바꿀 수 있나?

locklock 이이 생긴다생긴다?? 자연스런 일로 다중 사용자 시스템에서 transaction 을 유지하는 필수적인 mechanism 이다 현재 사용되고 있는 table,page,row 에 대한 다른 transaction 의 사용제한을 의미한다 lock 의 종류에 따라 제한정도(read 는 가능여부) 가 다르다 문제는 lock contention 이라 할 수 있는데, 즉 blocking 을 말한다

intent lock intent lock 이이 무엇인가무엇인가? (lock ? (lock 종류와종류와 대상대상))Table 에 걸리는 Lock 의 일종이다

PAGE / ROW Level Lock 종류

종류 1) Shared Lock 1) PAGE/ROW 를 select 할 때 발생한다 2) Shared Lock 이 걸린 PAGE/ROW 에 Shared Lock 이 동시에 같이 걸 수 있다

종류 2) Exclusive Lock 1) PAGE/ROW 에 대한 insert,update,delete 를 했을 경우 발생한다 2) Exclusive Lock 이 걸린 PAGE/ROW 에 어떤 종류의 Lock 도 허용하지 않는다

종류 3) Update Lock 1) PAGE/ROW 에 insert,update,delete 을 위해 읽어들일때 순간적으로 발생한다 2) PAGE/ROW 변경과 동시에 Exclusive Lock 으로 변환된다 3) Update mode 로 cursor 를 선언하여 row 를 fetch 하였을 경우, read 된 PAGE/ROW 에 대해 Update Lock 이 발생하며 다른 Transaction 에 대해서는 Shared Lock 만 허용됩니다

TABLE Level Lock 종류 종류 1) Intent Lock 1) Table 에 속한 PAGE/ROW 들 가운데 Lock 이 존재하는가를 나타내는 Lock 이다 2) Intent Shared Lock 과 Intent Exclusive Lock 으로 구분됩니다 Table 의 PAGE/ROW 중에 한 개라도 Shared Lock 이 있다면 Intent Shared Lock Table 의 PAGE/ROW 중에 한 개라도 Exclusive Lock 이 있다면 Intent Exclusive Lock

종류 2) Shared Lock 1) Table 에 속한 모든 PAGE/ROW 에 Shared Lock 을 필요한 경우에 사용된다 2) Table 에 많은 Shared Page/ROW Lock 으로 인한 Lock Promotion 경우 발생한다 3) Holdlock option 을 이용한 select 가 Full table scan 할 경우에 발생한다 4) nonclustered index 생성시에 발생한다

종류 3) Exclusive Lock 1) Table 에 속한 모든 PAGE/ROW 에 Exclusive Lock 을 필요한 경우에 사용된다 2) Table 에 많은 Exclusive Page/ROW Lock 으로 인한 Lock Promotion 경우 발생한다 3) Update 나 Delete 문장이 index 사용하지 않는 경우 발생한다 4) clustered index 생성시에 발생한다

19

Page 20: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

lock lock 발생과발생과 해제는해제는 언제인가언제인가??sql 문장이 수행되는 시점에 발생된다

Shared PAGE/ROW Lock 경우 PAGE/ROW 가 Read 된후 바로 해제된다

Exclusive PAGE/ROW Lock 경우 Commit/ Rollback 으로 해제된다

Select(Shared Lock)에 의한 Lock 의 해제 시점은 Holdlock 및 isolation level 에 따라 다르므로 주의하여야 한다

Holdlockselect 문장 실행 시 잡힌 Shared Page Lock 의 해제를 commit 이나 rollback 명령을 통해 명시적으로 해 주어야 풀리는 경우로 보통 조회 후 조회된 결과에 따른 변경(insert,update,delete)을 할 경우에 사용됩니다. Holdlock option 없이 조회한 경우는 page read후 바로 Lock 이 해제가 된다 ex) select * from test_tab holdlock where id > 100

isolation Levelisolation level 은 0,1, 3까지 transaction 시작 전 set transaction 명령으로 지정가능 합니다. isolation level 은 transaction 내에서 Select 문장에 의한 Shared Page Lock 의 시작과 해제시점을 정의하므로 Exclusive Lock 과는 상관 없음을 유의한다

1) isolation level 0 set transaction isolation level 0 명령에 의해 설정되며 select 명령 실행 시 Share Page Lock 을 필요로 하지 않습니다. 따라서 Page read 시에 그 Page 에 대한 어떠한 Lock 도 장애가 되지 않으며 select 문장의 holdlock option 은 아무런 효과가 없다 다른 transaction 에 의해 변경중인(exclusive page lock) page 에 대해서도 read 가 가능하다

2) isolation level 1 isql 에서 기본(default) mode 로 사용되며 select 시 읽혀지는 page 에 대해 순간적으로 Shared Page Lock 이 걸리며 읽힌후 바로 Lock 이 해제된다 select 문장에서 Holdlock option 을 주게되면 Page 를 읽을때 잡히는 Shared Page Lock 은 바로 해제가 되지 않으며 commit/rollback 명령에 의해서만 해제된다

3) isolation level 3 실행되는 모든 select 문에 대해 Holdlock option 을 준 효과를 발휘합니다. 따라서 Commit/Rollback 전 까지는 read 된 모든 page 에 대해서 Shared Page Lock 이 해제 되지 않으므로 유의 하여야 한다 Update Lock 은 cursor pointer 가 가리키고 있는 page 에 대해서만 잡힌다 Exclusive Lock 은 commit 과 함께 해제된다 isolation level 0 는 Share Lock 없이 read 한다 level 1 에서의 Shared Lock 은 Page read 후 바로 해제된다

lock lock 탐지하는탐지하는 방법은방법은??sp_who,sp_lock 통해서 할 수 있다

sp_who Server 에서 실행되는 Process(Thread)의 상태(status)를 확인합니다

20

Page 21: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

spid status loginame hostname blk dbname cmd ---- ------------ ------------- ------------- ---- ----------- ------------------------------ 1 recv sleep bird jazzy 0 master AWAITING COMMAND 2 sleeping NULL 0 master NETWORK HANDLER 3 sleeping NULL 0 master MIRROR HANDLER 4 sleeping NULL 0 master AUDIT PROCESS 5 sleeping NULL 0 master CHECKPOINT SLEEP 6 recv sleep rose petal 0 master AWAITING COMMAND 7 running sa helos 0 master SELECT 8 send sleep daisy chain 0 pubs2 SELECT 9 alarm sleep lily pond 0 master WAITFOR 10 lock sleep viola cello 8 pubs2 SELECT

8 번 process 에 의한 10 번 process 의 wait

sp_lock Lock 을 잡고 있는 Process ID 와 Table 및 Page 를 확인 한다

spid locktype table_id page dbname class---- ------------ ---------- ---- ------ --------------- 1 Ex_intent 1308531695 0 master Non cursor lock 1 Ex_page 1308531695 761 master Non cursor lock 1 Sh_intent 380528389 0 master Cursor Id 327681 1 Update_page 380528389 3752 master Cursor Id 327681 5 Ex_intent 144003544 0 userdb Non cursor lock 5 Ex_page 144003544 509 userdb Non cursor lock 5 Sh_intent 380528389 0 master objects_crsr 8 Ex_table 240003886 0 pubs2 Non cursor lock 8 Ex_page 112003436 2376 pubs2 Non cursor lock 8 Ex_intent-blk 112003436 0 pubs2 Non cursor lock

select Object_name(112003436)으로 Table 확인. 10 번 Process 에 대한 Blocking 을 의미(sp_who)

sp_object_stats table,index 의 lock 통계를 보여준다. lock scheme 변화의 indicator 가 된다

20 분내에 20 개의 high-contention table 을 본다sp_object_stats "00:20:00",20

sp_sysmon항목 "Logical Lock contention"으로 관찰한다

lock contention lock contention 줄이는줄이는 방법은방법은?? 프로그램에서 실행되는 SQL 이 좋은 Queryplan 을 갖고 실행될지라도 다중 사용자 환경에서 Lock 의 경합을 유도한다면 좋은 수행속도를 유지 할 수 없다

Tuning 시 Lock 의 경합이 있는지를 확인하는 절차가 꼭 필요하다

table design혹은 프로그램시에 각별한 주의를 필요로 한다

21

Page 22: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

현실적으로 수정이 불가하거나 프로그램의 Logic 흐름상 어쩔수 없다면 다음과 같은 방 법을 고려해 볼만 한다

1) table 의 lock schema 를 dol 로 바꾼다 lock 의 범위를 줄인다

2) max_row_per_page 를 이용한 Lock 을 분산시킨다 max_row_per_page 는 Data Page혹은 index Leaf Page 에 저장될수 있는 Row 의 최대 갯수를 제한하는 것으로 Table/index 를 생성할때 정의할 수 있습니다. 한 Row 의 변경이 나 조회가 Row 가 존재하는 Page 에 대한 Lock 이 걸리는 만큼 Row 를 좀 더 많은 Page 에 분산시켜 Lock 의 경합을 줄이고자 하는 목적에서 사용됩니다. 기본(default)값 은 0 인데 이것은 한 Page 에 저장되는 최대 Row 의 수를 제한하지 않는 것을 의미하며 Table 이나 Clustered index 경우 한 Page 에 최대 256 개의 Row 가 저장 가능합니다 syntax) create table newtable ( id numeric(18,0) identity, name char(8), address varchar(40) null) with max_row_per_page = 20

3) fillfactor 를 이용한 Lock 을 분산시킨다 fillfactor 는 index Leaf Page 에만 적용되는 것으로 한 index Page 공간에 대해 몇 퍼센트 를 inex entry 로 채울것인지 정의하는 Option 입니다. 만일 90 으로 정의했다면 한 Page 에 대한 여유공간을 적어도 10퍼센트를 확보하는 결과가 됩니다. 이것은 Lock 의 분산효 과뿐 아니라 변경으로 인한 Page Split 을 줄이는 효과가 있습니다. max_row_per_page 는 자동으로 유지관리 되지만 fillfactor 는 index 생성 당시만 적용됩니다

4) Table Partition 을 통한 Heap Table 을 2 개 이상으로 분산시킨다 Clustered index 가 존재하지 않는 Table 에 Row 를 insert 할 경우 새로운 Row 는 반드시 Table Data Page Chain 의 마지막 Page 에 저장되는데 이 Page 를 Heap 이라 하고 이런 Table 을 Heap Table 이라 합니다. 따라서 다중 사용자 환경에서 Heap Table 에 입력하는 경우 Heap(Last Page)에 대한 Lock 의 경합이 심해지는데 이럴 경우 Table Partition 기능을 이용하면 매우 효과적입니다. Table Partition 은 한 Table 에 대해 2 개 이상의 Data Page Chain 을 두는 것을 의미하며 이것은 2 개 이상의 Heap 이 존재함으로 해서 Lock 의 경합을 1/N 로 줄이는 효과가 있습니다. 또한 대량의 Data 를 BCP IN 하는 경우 매우 효과적입니다

syntax) alter table newtable partition 6 alter table newtable unpartition

5) table 을 partition 한다 (Hot spot heap 인 경우) hot spot 인 heap table 인 경우에 insert point 를 여러 개로 가져갈 수 있다

6) clustered index 를 만든다 hot spot 인 heap table 에 clustered index 를 만들면, last page 가 아닌 중간 page 에도 insert 가 일어난다

locklock 기다리는기다리는 시간을시간을 무한정에서무한정에서 일정시간으로일정시간으로 바꿀바꿀 수수 있나있나?? LOCK wait time 한계를 설정할 수 있다. (ASE Version 12 이상에서 지원된다)

22

Page 23: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

1) server-wide 도 setting sp_configure "lock wait period" [, no_of_seconds]

2) table 단위로 setting lock table table_name in {share | exclusive} mode [wait [no_of_seconds] | nowait]

3) connection 에 setting set lock { wait no_of_seconds | nowait }

수행중인 transaction 이 lock wait 상태에서 timeout 을 만나면 다음 message 가 나온다Msg 12205, Level 17, State 2:Server 'sagan', Line 1:Could not acquire a lock within the specified wait period. SESSION level wait period=300 seconds, spid=12, lock type=shared page, dbid=9, objid=2080010441, pageno=92300, rowno=0. Aborting the transaction.수행중인 transaction 은 rollback 된다

7.LOCK Promotion7.LOCK Promotion

23

Page 24: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

왜 lock promotion 이 일어나게 하는가? default 로 lock promotion 은 언제 일어나는가? lock promotion threshold 을 setting 하는 방법은? lock promotion 은 언제 일어나는가? row level lock -> page level lock -> table level lock 순으로 일어나는가?

왜왜 lock promotionlock promotion 이이 일어나게일어나게 하는가하는가?? lock 의 갯수가 많은 것은 lock 관리하는 resource 를 많이 사용하게 된다는 것이다만약, 1 table 에 lock 을 잡는 갯수가 너무 많아 진다면 결국 동시에 여러사람이 못 쓰는 상황이라는 것이고, lock 의 범위를 한 단계 높여 lock 의 갯수는 줄여 lock 관리하는 resource 는 줄이자는 것이다

defaultdefault 로로 lock promotionlock promotion 은은 언제언제 일어나는가일어나는가?? 한 table 에 한 task 또는 worker process 가 잡는 page 또는 row lock 이 200 개 이상이면 table level lock 으로 promotion 된다

1> sp_configure 'promotion'2> goParameter Name Default Memory Used Config Value Run Value ------------------------------ ----------- ----------- ------------ ----------- page lock promotion HWM 200 0 200 200 page lock promotion LWM 200 0 200 200 page lock promotion PCT 100 0 100 100 row lock promotion HWM 200 0 200 200 row lock promotion LWM 200 0 200 200 row lock promotion PCT 100 0 100 100

lock promotion thresholdlock promotion threshold 를를 settingsetting 하는하는 방법은방법은?? Server-widesp_setpglockpromote server, null, new_lwm, new_hwm, new_pct

sp_setrowlockpromote server, null, new_lwm, new_hwm, new_pct

또는 sp_configure '{page | row} lock promotion {LWM | HWM | PCT}', configvalue

Database-widesp_setpglockpromote 'database', 'database_name', new_lwm, new_hwm, new_pct

sp_setrowlockpromote 'database', 'database_name', new_lwm, new_hwm, new_pct

Objectsp_setpglockpromote 'table', 'table_name', new_lwm, new_hwm, new_pct

sp_setrowlockpromote 'table', 'table_name', new_lwm, new_hwm, new_pct

24

Page 25: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

lock promotionlock promotion 은은 언제언제 일어나는가일어나는가??task 가 작업하다가, 현재 table 에 잡은 lock 의 개수가LWM 보다 작으면, Lock promotion 한다LWM 와 HWM 사이이면, PCT 의 개수와 비교해 많으면, Lock Promotion 한다HWM 보다 크면, Lock promotion 한다

row level lock -> page level lock -> table level lock row level lock -> page level lock -> table level lock 순으로순으로 일어나는가일어나는가?? 그렇지 않다row level lock -> table level lock 또는 page level lock -> table level lock 으로 일어난다

8.Table lock schemes8.Table lock schemes

25

Page 26: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

Syntax Allpages Lock, Datapages Lock, Datarows Lock 이 어떻게 틀리는가? DOL(Data Only Lock :Datapages,Datarows)경우 transaction 유지되는가? lock scheme DOL <-> AOL 바꿀때, 어떤 절차로 해야하는가?

어떤 lock scheme 을 선택해야 되는가? DOL 사용시, Garbage 어떻게 없앨 수 있는가?

SyntaxSyntaxTable creation 시,Create table table_name (Column_name datatyppe [null | not null | identity], …Column_name datatyppe [null | not null | identity])[lock {allpages | datapages | datarows}]

Table 변경시,alter table table_namelock { allpages | datapages | datarows }

확인은 sp_help table_name 으로 한다

Allpages, Datapages, Datarows LockAllpages, Datapages, Datarows Lock 이이 어떻게어떻게 틀리는가틀리는가??

Allpages Datapages DatarowsIndex pages Lock 된다 Lock 걸리지 않는다 Lock 걸리지 않는다

Data pages Lock 된다 Lock 된다 Row level Lock된다

Clustered index

Sort 상태로 저장유지

처음 creation 때는 Sort 상태로 저장Data 변경됨에 따라 순서유지 못함

Row 가 delete시

Physical delete Logical delete

Row 길이 줄 때

Space 를 쓸수 있다 Space 는 쓸수 없다

관리 필요없다 때때로 reorg 작업을 해야 한다

DOL(Data Only Lock :Datapages,Datarows)DOL(Data Only Lock :Datapages,Datarows)경우경우 transactiontransaction 유지되는가유지되는가?? 유지된다실제적으로 lock 을 이용하지는 않지만, latch 라는 것을 이용해서 index 의 변경 시 다른 thread가 같은 index page 를 변경하는 일이 없도록 한다lock 은 변경 작업 시만 잡힌다

lock scheme DOL <-> AOL lock scheme DOL <-> AOL 바꿀때바꿀때, , 어떤어떤 절차로절차로 해야하는가해야하는가??STEP 1) 모든 nonclustered index 를 없앤다STEP 2) alter table 명령으로 lock scheme 을 바꾼다

26

Page 27: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

STEP 3) nonclustered index 를 재생성 한다

27

Page 28: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

어떤어떤 lock schemelock scheme 을을 선택해야선택해야 되는가되는가??Allpages Lock 고려 -> Datarows Lock 고려 -> Datapages Lock 고려한다

DOLDOL 사용시사용시, Garbage , Garbage 를를 어떻게어떻게 없앨없앨 수수 있는가있는가??2 가지 방법이 있다 자동적으로 하는 방법이다. 즉 housekeeper 가 하게 한다sp_configure “enable housekeeper”,1

reorg 를 사용해서 한다reorg { reclaim_space table_name[index_name] [with {resume|time = number of minutes}] |{ forwarded_rows table_name[index_name] [with {resume|time = number of minutes}] |reorg { compact table_name[index_name] [with {resume|time = number of minutes}] |reorg { rebuild table_name[index_name] [with {resume|time = number of minutes}] }

Subcommand Unforwards rows? Compacts space? Improves clustering?Reclai

m_spaceN Y N

Forwarded_rows

Y N 약간

Compact

Y Y 약간

Rebuild

y Y Y

Reclaim_space 는 현재 사용되지 못하는 영역을 다시 쓸 수 있게 한다 Forwarded_rows 는 해당 row 가 그 자리에서 update 가 힘들어 다른 page 로 옮겨 가면서 원래 있던 자리에 옮겨가는 page 를 남겨놓는 경우이다결국 1page 를 읽어서 처리하려던 작업을 forwarded 경우는 2 개 이상의 page 를 읽어야 하는 경우가 생기는 데 이런 row 를 없애준다 compact 는 reclaim_space 와 forwarded rows 를 둘 다 하는 경우이다 rebuild 는 전체 table 을 다시 만드는 것으로 모든 index 또한 새롭게 만든다

optdiag statistics 의 수행결과로forwarded row count,deleleted row count,data page clustering ratio 를 알 수 있다

이것을 기준으로 reorg 수행여부를 결정한다.clustering ratio 는 1 에 가까울수록 더 효과적이다

28

Page 29: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

9.DEADLOCK9.DEADLOCK

deadlock 이 왜 발생하나? deadlock 일으키는 시뮬레이션 deadlock 의 원인을 찾는 방법은? deadlock 을 ASE 는 어떻게 처리하나? deadlock 을 방지하는 방법은?

deadlockdeadlock 이이 왜왜 발생하나발생하나??2 개또는 그이상의 User Process 가 Data,Index Page 또는 table 에서분리되기 위한 Lock 을 가질 때 생성된다

deadlock deadlock 일으키는일으키는 시뮬레이션시뮬레이션1> begin tran2> go1> update A set col2 = 'time 1'2> where col1 = '1'3> go(1 row affected)1> begin tran2> reset1> update A set col2 = 'time 3'2> where col1 = '100'3> goMsg 1205, Level 13, State 1:Server 'ASE12A', Line 1:Your server command (family id #0, process id #8) encountered a deadlocksituation. Please re-run your command.1>

1> use pubs22> go1> begin tran2> go1> update A set col2 = 'time 2'2> where col1 = '100'3> go(1 row affected)1> update A set col2 = 'time 4'2> where col1 = '1'3> go

deadlockdeadlock 의의 원인을원인을 찾는찾는 방법은방법은?? DeadLock 추적정보는 DBCC trace flag,1204 와 3605 를 on 하여 생성한다1204 : SQL Server 에게 deadlock 이 발생하면 deadlock 추적, 정보를 생성하도록 지시한다3605 : SQL Server 에게 deadlock 이 발생하면 deadlock 정보 error log file 에 출력한다해당 trace flag 를 on 하려면 sa role 을 가진 login 으로 login 하여야 한다

항상 trace flag 를 on 하려면 :dataserver –d /dev/rsd0 –sSYBASE –e /sybase/install/SYBASE.log -I /home/sybase/interfaces –M /home/sybase –T1204 –T3605

29

Page 30: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

00:00000:00001:2000/12/01 09:54:14.06 server Deadlock Id 1 detectedDeadlock Id 1: detected. 1 deadlock chain(s) involved.

Deadlock Id 1: Process (Familyid 8, 8) (suid 1) was executing a UPDATE command at line 1.SQL Text: update A set col2 = 'time 3' where col1 = '100'

Deadlock Id 1: Process (Familyid 1, 1) (suid 1) was executing a UPDATE command at line 1.SQL Text: update A set col2 = 'time 4' where col1 = '1'

Deadlock Id 1: Process (Familyid 0, Spid 1) was waiting for a 'update row' lockon row 0 page 817 of the 'A' table in database 5 but process (Familyid 8, Spid 8) already held a 'exclusive row' lock on it.Deadlock Id 1: Process (Familyid 0, Spid 8) was waiting for a 'update row' lockon row 0 page 1101 of the 'A' table in database 5 but process (Familyid 1, Spid1) already held a 'exclusive row' lock on it.

Deadlock Id 1: Process (Familyid 0, 1) was chosen as the victim. End of deadlock information.

주의 사항 :DEADLock trace flag 를 설정하는 것은 SQL server 의 performance 를 크게 떨어 뜨릴 수가 있다. 해당 trace flag 는 debug 를 할 경우에만 사용 하는 것이 좋다

deadlockdeadlock 을을 ASEASE 는는 어떻게어떻게 처리하나처리하나??해당 DeadLock 이 발생 하면 Lock Manager 가 해당 process 의 CPU Time 을 계산하여 Time 이 적은 process 를 kill 시킨다

deadlockdeadlock 을을 방지하는방지하는 법법 data-only 로 locking scheme 을 바꾸는 것을 고려한다 모든 transaction 에서 같은 순서로 table 을 access 하게 한다 가능한한 transaction 을 작게한다 가능한한 transaction 을 commit 한다 transaction 안에서 user 의 input 을 기다리는 것을 피한다

deadlock 이 발생하면 error # 1205 를 받으므로 다시 sql 문장을 시키던지 아니면 error 내용을 user 에게 통보하고 끝내든지 해야 할 것이다

30

Page 31: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

10.M10.Memory emory ASE 의 memory structure 는? memory 구조에 영향주는 parameter 는 Data Cache 구조는 Optimizer 의 buffer pool 선택은? cache strategy 이란?

ASEASE 의의 memmemory ory sstructuretructure 는는??

ASE 가 start 할때 고정적으로 확보한다

Kernel

Server internal Structure

Procedure Cache

Data Cache

Additional Network Memory

Dataserver(Engine) 실행 모듈을 말합니다.

Server에 연결된 Thread에 대한 Task Contexts정보, Lock 정보 , Default Network Memory를포함합니다.

사용된 Stored Procedure, Trigger의 실행 모듈 그리고 Query Plan을 포함합니다.

읽혀진 Data Page, Index Page 그리고 Log page를 포함합니다.Buffer Pool,Named Cache가 만들어지는 영역입니다.

Network Packet Size를 512 Byte이상으로사용하는 Client를 위해 사용되는 Memory. sp_configure 로 설정하지 않으면 따로 잡히지 않습니다.

Total Mem

ory

memory memory 구조에구조에 영향주는영향주는 parameterparameter 는는?? sp_configure 'total memory' ASE 가 start 할 때, 잡고 올라오는 총 memory량을 지정한다 단위는 page 로 1 page 가 512 byte 이다

sp_configure "user connection"

sp_configure 'procedure cache percent' procedure cache 영역이 data cache 영역의 몇 %인지를 결정한다

sp_configure 'additional network memory' client 에서 default packet 보다 큰 packet 을 사용하는 경우 설정되어야 한다 만일 2 개의 thread(process)가 packet size 2048 로 실행 된다면 (2048 * 3 + overhead) 이상 설정되어야 합니다. 여기서 3 은 read /write/overflow buffer 각 1 개씩을 말하며 overhead 는 2048*3*0.02 입니다

31

Page 32: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

ASE internal structure 영역의 size 'number of device','user connection','open databases','number of lock' 등에 영향을 받는다

Data CacheData Cache 구조는구조는?? 실제 data 에 대해 작업하는 공간이다

Data Cache 의 크기는 'Total Memory' 크기에 영향을 받는다

현실적으로 'Total Memory' size 는 Physical Memory 크기에 제한을 받는다

SYBASE 가 사용하는 'Total Memory'의 크기를 많이 잡아주면 좋을것 같으나 상대적으로 SYBASE 와 다른 프로그램들과의 Memory 경합으로 인한 시스템의 과도한 스와핑과 페이지폴트로 오히려 수행 속도를 저하시키는 역효과를 내게 된다. 따라서 Syetem Monitoring 을 통한 Total Memory 의 적절한 조정이 필요하다

Data Cache 는 1 개의 default Cache 와 DBA 에 의해 만들어진 Named Cache 로 구성된다. 각 Cache 에는 1 개 이상의 Buffer Pool 로 이루어지며 Cache 내에 I/O 단위별로 Buffer Pool 을 만들 수 있다. 각 Cache 내에 2K Buffer Pool 은 기본으로 존재한다

2K Buffer Pool

2K Buffer Pool 2K Buffer Pool

16K Buffer Pool

8K Buffer Pool4K Buffer Pool

16K Buffer Pool

Default Data Cache my_data_cache my_log_cache

Named Cache

Default Data Cache 1) 기본으로 존재하는 Cache 2) 이 영역을 일부를 떼어 또 다른 Named Data Cache 를 만들 수 있다 3) 특정 Named Cache 에 Binding 이 되지 않은 모든 Object 에 대한 Cache 영역으로 사용된다 4) Default Cache 역시 기본으로 2K I/O Buffer Pool 을 포함하며 4K,8K,16K I/O 단위의 Buffer Pool 을 만들 수 있다

Named Cache 1) Database, Table, index, Table 의 Text Column 등과 Binding 된다 2) 자주 사용되는 Object 를 Named Cache 와 Bind 시켜 Cache Hit Ratio 를 높인다

32

Page 33: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

3) SMP환경에서 Cache 에 대한 Dataserver Engine 간의 Memory Contention(spinlock)을 줄이는 효과도 있다 4) Named Cache 생성및 특정 Object 로 Bind 는 상대적으로 Defaut Data Cache 의 크기 축소를 야기시켜 전체적인 수행속도에 영향을 미칠수 있으므로 Cache Size 결정에 신중을 기해야 합니다

OptimizerOptimizer 의의 buffer pool buffer pool 선택은선택은?? Buffer Pool 1) Data Cache 내에 I/O 단위별(2,4,8,16K)로 1 개씩 생성될 수 있다 2) Query 성질에 따른 적절한 Buffer Pool 의 선택은 Optimizer 에 결정된다 3) Query 할 때 Hint 혹은 Set 명령에 의해 선택될 수 있다 Optimizer 가 Query Plan 을 결정할때 사용되는 Data Cache 에 2 개 이상의 Buffer Pool 이 존재 할 경우 Plan 에 적당한 Buffer Pool 도 함께 결정된다

Large I/O Buffer Pool 이 사용되는 경우는 다음과 같다 1) Table Scan 을 필요로 하는 Query 2) Clustered Index 에 대한 Range Scan 을 필요로 하는 Query 3) Nonclustered Index Leaf Page Scan 을 필요로 하는 Query 4) Text/Image Data 를 조회하는 Query 5) BCP in/out 을 하는 경우 6) Update Statistics, Dbcc Checkdb, Dbcc Checktable 경우 위와 같은 경우를 만족하는 Query 라 할지라도 Largre I/O 를 실행하기 위해선 다음과 같은 조건을 만족해야 한다 1) Large I/O 에 의해 한번에 읽혀지는 Page 중 하나라도 2K Buffer Pool 내에 존재하지 않아야 한다 2) Large I/O 에 의해 한번에 읽혀지는 Page 중 에는 Allocation Unit 이나 OAM Page 를 포함하지 않아야 한다 3) 읽혀지는 Table 이나 Index 에 대해 Prefetch Option 이 Enable 되 있어야 한다 예) 1> sp_cachestrategy pubs2, titles

object name index name large IO MRU ---------------- ---------------- -------- -------- titles NULL ON ON

4) Set Prefetch Off 명령을 Query 시적전에 실행되지 않아야 한다

Large I/O Buffer 사용에 있어 주의할 점읽어 들이고자 하는 Page 를 시작으로 Logical Page Number 가 한번에 연속적인 2 Page, 4Page 혹은 8Page 를 읽어 들인다는 의미 이므로, 만일 읽어 들이는 Table 혹은 Index Page Chain 의 Logical Page Number 가 논리적으로 연속적이지 않다면 효과가 없다

변경이 잦은 Table 에 대해 Large I/O 의 효과를 배가 시키기 위해선 정기적으로 BCP Out 후 BCP in 하는 것도 하나의 방법이라 할 수 있다

Cache StrategyCache Strategy 이란이란?? Buffer Pool 내의 Cache Buffer Unit 의 Size 는 sp_poolconfig 명령에 의해 결정되며 Buffer 의 관리는 MRU-LRU Chain 에 의해 유지된다. MRU-LRU Chain 은 각 Buffer Pool 마다 따로

33

Page 34: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

존재하며 , 한정된 Buffer 용량에 대해 가장 최근에 사용된(Most Recently Used) Page 를 우선으로 Buffer Pool 에 존재 시킴으로 Cache Hit율을 높이려는 메모리 관리 기법이다또한 sp_poolconfig 명령으로 Buffer 를 생성할때 일정 Size 의 영역을 Wash 영역으로 정의 할 수 있는데 이것은 최근에 사용되지 않은 Buffer(Least Recently Used) 혹은 변경된 Buffer 를 Wash Area 로 놓아 Checkpoint 혹은 Housekeeper 프로세스 기동시에 Disk 로 Write 하여 Free Buffer를 확보 하는데 목적이 있다. MRU-LRU Chain 에서 Wash Area 의 시작 되는 Buffer 를 Wash Marker 라 한다

LRU Replacement Strategy가장 최근에 읽혀진(사용된) Page 를 MRU-LRU Chain 의 MRU 쪽 가장 끝에 놓아 Physical Read 를 최소화하는 Cache 관리 기법이다. Databse Meta Data, Point Query , OAM Page 등이 Caching 될 때 사용된다

MRU Replacement Strategy읽혀진 Page 를 MRU-LRU Chain 의 Wash Marker 바로 앞에 끼워넣는 방법으로 Table Scan, Index Leaf Scan 등 앞으로 재 사용될 가능성이 적다고 판단되는 Page 를 LRU 쪽에 둠으로서 MRU 기법에 의해 읽혀진 Page 를 좀 더 오랫동안 Cache 에 유지 시키는 효과가 있다

MRU(Most Recently Used) LRU(Least ..)Wash Marker

select * from employee (Full Table Scan)

Wash Area

select * from employeewhere id = 23659(index Point Query)

Page in(2,4,8,16K Unit) Page in

(2,4,8,16K Unit)

Page Out(2,4,8,16K Unit)

이동Dirty Buffer

Disk Write

CheckpointerHousekeeper(Dirty Buffer)

Buffer Pool

Data Cache 사용의 권고 사항Tempdb 를 Named Cache 와 Bind 한다면 Named Cache 내에 16K Buffer Poold 를 만듭니다. select into 명령은 16K I/O 가 효과적이다자주 사용되는 Database 의 Log 를 Named Cache 와 Bind 시키며 Named Cache 에 4K Buffer Pool 을 만들어 준다. Log 에 대한 Default I/O Size 는 4K 이다Meta Data (sysindexes,sysobjects,syscolumns)에 대해 각각 512K 정도의 Named Cache 와 Bind 하면 효과가 좋다Code Table 과 같이 Size 는 적고 자주 접근되는 Table 에 대해 Named Cache 와 Bind 시킨다Named Cache 는 결국 Default Cache 로부터 만들어지고 Bind 되지 않은 모든 Object 에 대한 Caching 은 Default Cache 에서 이루어 지는 만큼, Named Cache 의 남용으로 인한 Default Cache 의 고갈에 주의해야 합니다Cache 를 변경 전후에 대한 Monitoring 을 철저히 하여 효과를 확인합니다

34

Page 35: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

Default Data Cache 및 Buffer Pool 의 상태확인 1> sp_poolconfig 'default'2> go Cache Name Status Type Config Value Run Value ------------------------------ ----------- -------- ------------------ -------------- default data cache Active Default 0.00 Mb 14.00 Mb(1 row affected) ----------------- --------------- Total 0.00 Mb 14.00 Mb==============================================================Cache: default data cache, Status: Active, Type: Default Config Size: 0.00 Mb, Run Size: 14.00 MbIO Size Wash Size Config Size Run Size -------- --------- ------------ ------------ 2 Kb 512 Kb 7.00 Mb 14.00 Mb (return status = 0)

Named Data Cache 를 Default Data Cahe 의 2K Buffer Pool 로부터 생성1> sp_cacheconfig 'mycache','7M'2> go(return status = 0)SYBASE Shutdown and Reboot

생성된 Named Cache 의 확인1> sp_helpcache2> goCache Name Config Size Run Size Overhead------------------------ ------------- ------------ -------------- default data cache 0.00 Mb 14.00 Mb 0.72 Mbmycache 7.00 Mb 0.00 Mb 0.00 Mb Memory Available For Memory ConfiguredNamed Caches To Named Caches-------------------- ------------------------- 14.00 Mb 7.00 Mb There is 7.00 Mb of memory left over that will be allocated to the default cache ------------------ Cache Binding Information: ------------------ Cache Name Entity Name Type Index Name Status----------------- ----------------- -------- ----------------- ---------(return status = 0)

SYBASE Shutdown and Rebooting

생성된 mycache 내에는 2K Buffer Pool밖에 없으므로 16K Buffer Pool 을 생성한다1> sp_poolconfig 'mycache','3M','16K'2> go(return status = 0)1> sp_poolconfig 'mycache'2> go Cache Name Status Type Config Value Run Value ------------------------- --------- -------- ------------- ---------------

35

Page 36: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

mycache Active Mixed 7.00 Mb 7.00 Mb ------------- --------------- Total 7.00 Mb 7.00 Mb============================================================Cache: mycache, Status: Active, Type: Mixed Config Size: 7.00 Mb, Run Size: 7.00 Mb

IO Size Wash Size Config Size Run Size -------- --------------- ---------------- ------------ 2 Kb 512 Kb 0.00 Mb 4.00 Mb 16 Kb 608 Kb 3.00 Mb 3.00 Mb(return status = 0)

mycache 를 mydb 와 Binding 한다1> sp_bindcache mycache, mydb2> go(return status = 0)

mycahe 의 최종 상태를 확인한다1> sp_helpcache 'mycache'2> go

Cache Name Config Size Run Size Overhead------------------------ ----------------- -------------- -------------- mycache 7.00 Mb 7.00 Mb 0.39 Mb

------------------ Cache Binding Information: ------------------

Cache Name Entity Name Type Index Name Status------------------ ----------------- ------- ----------------- --------mycache mydb database V(return status = 0)1> sp_poolconfig 'mycache'2> goCache Name Status Type Config Value Run Value ------------------------------ --------- -------- ----------------- --------------- mycache Active Mixed 7.00 Mb 7.00 Mb ----------------- --------------- Total 7.00 Mb 7.00 Mb==============================================================Cache: mycache, Status: Active, Type: Mixed Config Size: 7.00 Mb, Run Size: 7.00 Mb IO Size Wash Size Config Size Run Size -------- --------- ------------ ------------ 2 Kb 512 Kb 0.00 Mb 4.00 Mb 16 Kb 608 Kb 3.00 Mb 3.00 Mb(return status = 0)

Binding 한 Database 에 있는 Table 을 조회하는 Query 에 대해 Queryplan 을 확인한다1> set showplan on2> go1> set noexec on2> go1> select test_tab1.id ,test_tab2.name from testtab1, test_tab22> where testtab1.id = test_tab2.id

36

Page 37: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

3> go

QUERY PLAN FOR STATEMENT 1 (at line 1).

37

Page 38: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

STEP 1 The type of query is SELECT.

FROM TABLE test_tab2 Nested iteration. Table Scan. Ascending scan. Positioning at start of table. Using I/O Size 16 Kbytes. Outer Table 에 대해 Table With LRU Buffer Replacement Strategy. Scan 을 16K Buffer Pool 에 대해 실행

FROM TABLE test_tab1 Nested iteration. Using Clustered Index. Index : ctx_test_tab2 Ascending scan. Positioning by key. Keys are: id Using I/O Size 2 Kbytes. inner Table 에 대해선 2K With LRU Buffer Replacement Strategy. Buffer Pool 사용

11.ASE basic thread 12.현재 ASE 는 무엇을 하나

13.ASE configuration

38

Page 39: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

14.CHARSET14.CHARSET eucksc 로 변경하는 방법? 데이터의 영문대소문자를 구분 안하게 할 수 있는가? UNIX 에서 한글이 안된다? SQL Advantage 에서 한글이 안된다?

eucksceucksc 로로 변경하는변경하는 방법방법??STEP 1) resource file 을 작성한다$SYBASE/ASE-12_0/init/sample_resource_files/sqlloc.rs 을 기본으로 해서 작성한다5군데를 수정한다sqlsrv.server_name : charset 을 바꾸려는 ASE SERVER 명을 넣는다sqlsrv.sa_login : sasqlsrv.sa_password : sa 의 password 를 넣는다sqlsrv.default_characterset : eucksc 를 넣는다sqlsrv.sort_order : bin_euckscsybinit.release_directory: USE_DEFAULTsqlsrv.server_name: ase12 sqlsrv.sa_login: sasqlsrv.sa_password: sybtech1sqlsrv.default_language: USE_DEFAULTsqlsrv.language_install_list: USE_DEFAULTsqlsrv.language_remove_list: USE_DEFAULTsqlsrv.default_characterset: euckscsqlsrv.characterset_install_list: USE_DEFAULTsqlsrv.characterset_remove_list: USE_DEFAULTsqlsrv.sort_order: binary_eucksc

STEP 2) sqllocres -r 을 사용해서 charset 바꾸는 작업을 한다 (꼭, ASE 가 START 상태여야함)내부적으로 바뀌는 내용이 화면과 errorlog 에 나온다이 작업이 끝나면, ASE Server 가 저절로 shutdown 된다[syb-sun:/ase/ase12/ASE-12_0/init/sample_resource_files 62 ] sqllocres -r sqllossqllocres: Installing character set 'EUC KSC' in the Adaptive Server...00:00000:00001:2000/12/07 11:55:19.70 server Configuration file '/ase/ase12/as.00:00000:00001:2000/12/07 11:55:19.72 server The configuration option 'allow u.00:00000:00001:2000/12/07 11:55:19.88 server Configuration file '/ase/ase12/as.00:00000:00001:2000/12/07 11:55:19.91 server The configuration option 'allow u.sqllocres: Character set 'EUC KSC' was successfully installed in the AdaptiveServer.sqllocres: Installing sort order 'Binary ordering, for the EUC KSC characterset (eucksc)' in the Adaptive Server...00:00000:00001:2000/12/07 11:55:19.99 server Configuration file '/ase/ase12/as.00:00000:00001:2000/12/07 11:55:20.00 server The configuration option 'allow u.00:00000:00001:2000/12/07 11:55:20.06 server Configuration file '/ase/ase12/as.00:00000:00001:2000/12/07 11:55:20.08 server The configuration option 'allow u.sqllocres: Sort Order 'Binary ordering, for the EUC KSC character set (eucksc)'was successfully installed in the Adaptive Server.sqllocres: Making 'EUC KSC' the Adaptive Server's default character set...sqllocres: Making 'Binary ordering, for the EUC KSC character set (eucksc)' theAdaptive Server's default sort order...00:00000:00001:2000/12/07 11:55:20.14 server Configuration file '/ase/ase12/as.00:00000:00001:2000/12/07 11:55:20.16 server The configuration option 'allow u.00:00000:00001:2000/12/07 11:55:20.33 server Configuration file '/ase/ase12/as.00:00000:00001:2000/12/07 11:55:20.34 server The configuration option 'default.

39

Page 40: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

00:00000:00001:2000/12/07 11:55:20.34 server WARNING: *************************00:00000:00001:2000/12/07 11:55:20.34 server Default char set being reconfigur:00:00000:00001:2000/12/07 11:55:20.34 server old charset ID = 1 new cha000:00000:00001:2000/12/07 11:55:20.33 server Configuration file '/ase/ase12/as.00:00000:00001:2000/12/07 11:55:20.34 server The configuration option 'default.00:00000:00001:2000/12/07 11:55:20.34 server WARNING: *************************00:00000:00001:2000/12/07 11:55:20.34 server Default char set being reconfigur:00:00000:00001:2000/12/07 11:55:20.34 server old charset ID = 1 new cha000:00000:00001:2000/12/07 11:55:20.48 server Configuration file '/ase/ase12/as.00:00000:00001:2000/12/07 11:55:20.49 server The configuration option 'allow u.01:00000:00001:2000/12/07 11:55:20.61 server Shutdown with nowait detected - S.01:00000:00001:2000/12/07 11:55:20.68 server SQL Server shutdown by request.01:00000:00001:2000/12/07 11:55:20.68 kernel ueshutdown: exiting

sqllocres: The Adaptive Server's default character set is now 'EUC KSC'.sqllocres: The Adaptive Server's default sort order is now 'Binary ordering,for the EUC KSC character set (eucksc)'.sqllocres: Done

STEP 3) ASE 를 start 한뒤, errorlog 내용을 확인한다00:00000:00001:2000/12/07 17:26:58.44 server SQL Server's default sort order is:00:00000:00001:2000/12/07 17:26:58.44 server 'bin_eucksc' (ID = 50)00:00000:00001:2000/12/07 17:26:58.44 server on top of default character set:00:00000:00001:2000/12/07 17:26:58.44 server 'eucksc' (ID = 150).

STEP 4) isql 로 접근을 시도하면, 다음 message 가 나온다UNIX] isql -Usa -Psybtec1Msg 2401, Level 11, State 2:Character set conversion is not available between client character set 'iso_1'and server character set 'eucksc'.No conversions will be done.

STEP 5) sp_configure 로 conversion 기능을 수행할 수 있게 한다1> sp_configure "disable character set",12> go00:00000:00001:2000/12/07 12:06:10.24 server Configuration file '/ase/ase12/as.00:00000:00001:2000/12/07 12:06:10.25 server The configuration option 'disable. Parameter Name Default Memory Used Config Value Run Value ------------------------------ ----------- ----------- ------------ ----------- disable character set conversi 0 0 1 0

(1 row affected)sConfiguration option changed. Since the option is static, Adaptive Server mustbe rebooted in order for the change to take effect.(return status = 0)

STEP 6) 다시, shutdown 과 startserver 를 수행한다

STEP 7) locales.dat 파일을 바꾼다[sun_svr4] ; from Solaris International Developer's Guide ;ISBN 0-13-031063-8 ; refer to "man setlocale()"locale = ko, us_english, eunksc

40

Page 41: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

STEP 8) 확인한다 1> sp_helpsort2> go

Collation Name Collation ID ------------------------------ ------------

Loadable Sort Table Name ------------------------------

Sort Order Description

------------------------------------------------------------------ Character Set = 150, eucksc Extended Unix Code for KSC-5601. Class 2 Character Set Sort Order = 50, bin_eucksc Binary sort order for Korean using the EUC KSC character set ( eucksc).(return status = 0)

"eucksc"를 사용해야 되는 경우 :

한글 data 에 대하여 결과가 잘못나오는 경우 예 1) 이름이 '강봉직', '혜은이' 가 있을 때 select name from table where name like '%봉%' 을 하면 '강봉직'만 나오는 것이 아니라 혜은이도 나온다.

예 2) 한글 data 와 영문 data 를 함께 사용할 때 upper(), lower() function 을 사용하면 한글 data 가 깨진다

Client

1) OCDK 10.0.3 을 사용할 때 STEP 1) locales.dat file 에서 iso_1 을 eucksc 로 바꾼다 STEP 2) locales/english directory 에 eucksc directory 를 만들고 iso_1 의 모든 file 을 eucksc 로 copy 한다 STEP 3) charsets directory 에 eucksc directory 를 만들고 iso_1 의 모든 file 을 eucksc 로 copy 한다

2) OCDK 11.1 을 사용할 때 STEP 1) 위의 a,b,c 를 한 다음 STEP 2) charsets/eucksc directory 에서 iso_1.cfg file 을 eucksc.cfg file 로 move 한다 STEP 3) charsets/utf8 directory 에서 iso_1.ctb file 을 eucksc.ctb file 로 copy 한다 STEP 4) charsets/utf8 directory 에 있는 utf8.cfg file 에 eucksc 를 추가한다

데이터의데이터의 영문대소문자를영문대소문자를 구분구분 안하게안하게 할할 수수 있는가있는가?? 할 수 있다. 단, 해당 charset 의 sort 중에서 nocase 를 지원하는 게 있어야 한다

STEP 1)보통 $SYBASE/charsets 에서 보면 지정된 charset directory 가 있는지 확인하고 다음과 같이 보면 nocase 로 시작하는 sort order 종류가 있는지 확인한다 [syb-sun:/ase/ase12/charsets/iso_1 49 ] ls *.srt

41

Page 42: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

binary.srt espdict.srt noaccent.srt nocasepr.srtdictiona.srt espnoac.srt noaccents.srt nocasepref.srtdictionary.srt espnocs.srt nocase.srt해당 file 을 열어보면, sort id 와 osrt name 을 찾을 수 있다[syb-sun:/ase/ase12/charsets/iso_1 50 ] cat nocase.srtclass = 0x01 ; Class `1' sort orderid = 0x34 ; Unique ID # (52) for the sort ordername = nocase_iso_1 ; Western-European, case-insensitivemenuname = "Dictionary order, case insensitive."charset = iso_1

STEP 2)sqlloc.rs 의 내용을 바꾼다ybinit.release_directory: USE_DEFAULTsqlsrv.server_name: ase12sqlsrv.sa_login: sasqlsrv.sa_password: sybtech1sqlsrv.default_language: USE_DEFAULTsqlsrv.language_install_list: USE_DEFAULTsqlsrv.language_remove_list: USE_DEFAULTsqlsrv.default_characterset: iso_1sqlsrv.characterset_install_list: USE_DEFAULTsqlsrv.characterset_remove_list: USE_DEFAULTsqlsrv.sort_order: nocase_iso_1

STEP 3)sqllocres -r 을 수행시킨다sqllocres -r sqlloc.rssqllocres: Making 'Case-insensitive dictionary sort order for use with severalW...' the Adaptive Server's default sort order...00:00000:00001:2000/12/08 13:06:48.79 server Configuration file '/ase/ase12/as.00:00000:00001:2000/12/08 13:06:48.81 server The configuration option 'allow u.00:00000:00001:2000/12/08 13:06:48.94 server Configuration file '/ase/ase12/as.00:00000:00001:2000/12/08 13:06:48.95 server The configuration option 'default.00:00000:00001:2000/12/08 13:06:48.95 server WARNING: *************************00:00000:00001:2000/12/08 13:06:48.95 server Default sort order being reconfig:00:00000:00001:2000/12/08 13:06:48.95 server old sortord ID = 50 new sort ID=5200:00000:00001:2000/12/08 13:06:49.08 server Configuration file '/ase/ase12/as.00:00000:00001:2000/12/08 13:06:49.09 server The configuration option 'allow u.01:00000:00001:2000/12/08 13:06:49.32 server Shutdown with nowait detected - S.01:00000:00001:2000/12/08 13:06:49.32 server SQL Server shutdown by request.01:00000:00001:2000/12/08 13:06:49.32 kernel ueshutdown: exitingsqllocres: The Adaptive Server's default sort order is now 'Case-insensitivedictionary sort order for use with several W...'.sqllocres: Done

STEP 4)sp_configure 로 다음을 한다1> sp_configure "default sortorder id",522> go00:00000:00001:2000/12/08 12:47:44.35 server Configuration file '/ase/ase12/as.00:00000:00001:2000/12/08 12:47:44.36 server The configuration option 'default.00:00000:00001:2000/12/08 12:47:44.36 server WARNING: *************************00:00000:00001:2000/12/08 12:47:44.36 server Default sort order being reconfig:00:00000:00001:2000/12/08 12:47:44.36 server old sortord ID = 50 new sor2You have just reconfigured SQL Server's default sort order. System tableindexes will be rebuilt when you reboot the SQL server. Parameter Name Default Memory Used Config Value Run Value ------------------------------ ----------- ----------- ------------ -----------

42

Page 43: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

default sortorder id 50 0 52 50

(1 row affected)Configuration option changed. Since the option is static, Adaptive Server mustbe rebooted in order for the change to take effect.(return status = 0)1> shutdown2> go

STEP 5)shutdown 한 뒤, rebooting 하고, 확인한다1> sp_helpsort2> go Collation Name Collation ID ------------------------------ ------------

Loadable Sort Table Name ------------------------------

Sort Order Description

------------------------------------------------------------------ Character Set = 1, iso_1 ISO 8859-1 (Latin-1) - Western European 8-bit character set. Sort Order = 52, nocase_iso_1 Case-insensitive dictionary sort order for use with several We stern-European languages including English, French, and German . Uses the ISO 8859-1 character set.Characters, in Order

------------------------------------------------------------------ ! " # $ % & ' ( ) * + , - . / : ; < = > ? @ [ \ ] ^ _ ` { | } ~ ??????????????????????????????? ???0 1 2 3 4 5 6 7 8 9 A=a ??????????????B=b C =c ??D=d E=e ????????F=f G=g H=h I=i ????????J =j K=k L=l M=m N=n ??O=o ????????????P=p Q=q R=r S =s ?T=t U=u ????????V=v W=w X=x Y=y ?? Z=z

STEP 6)실제로 select 문장에서 대/소문자를 구분 안하는 것을 test 한다1> select * from TESTTAB2 2> go col1 ---------- AAAAABBBBB AaAaAbBbBb aAaAaBbBbB aaaaabbbbb

(4 rows affected)

1> select * from TESTTAB2 where col1 = 'aaaAaBBBbB'2> go col1 ---------- AAAAABBBBB aaaaabbbbb AaAaAbBbBb aAaAaBbBbB

(4 rows affected)

43

Page 44: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

UNIXUNIX 에서에서 한글이한글이 안된다안된다??STEP 1)해당 platform 을 찾는다[UNIX] echo $SYBPLATFORMsun_svr4

STEP 2)$LANG 을 찾는다[UNIX ] echo $LANGko

STEP 3)ASE 가 사용하는 charset 을 찾는다 (ASE 의 errorlog 에서)00:00000:00001:2000/12/07 17:26:58.44 server on top of default character set:00:00000:00001:2000/12/07 17:26:58.44 server 'eucksc' (ID = 150).

STEP 4)locales.dat 에서 $SYBPLATFORM 찾고 locale = default, us_english, iso_1 라고 적힌 line 을 복사해 새로운 LINE 을 만든다. default 를 $LANG 으로 바꾸고,iso_1 을 charset 으로 바꾼다[sun_svr4] ; from Solaris International Developer's Guide ;ISBN 0-13-031063-8 ; refer to "man setlocale()"locale = ko, us_english, eunksc

SQL AdvantageSQL Advantage 에서에서 한글이한글이 안된다안된다??메뉴바의 4 번째 (Global Preference) 선택 -> Miscellaneous -> Font -> script -> 한글 을 선택한다

ADMIN -2 (3gl,open client 관련)

44

Page 45: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

1.Esqlc Esqlc 란? precompile 에서 nohold lock unchained Cursor 사용 시 고려할 점은? Array Binding 이란? Datatype 호환은? Persistent Binding 이란 Text/Image Datatype 있다면? CGI program 을 위한 sample insert 에서 array 변수를 사용하는 예 stored procedure 를 사용하는 법? image 처리하는 방법은? Application Name 등록방법은? datatype 호환

EsqlcEsqlc 란란?? ASE server 의 data 를 access 하거나 update 하는 C Program 을 가능하게 한다 SQL 문장은 EXEC SQL 다음에 명시해서, precompile(cpre)을 통해서 Open Client 의 Function-calll 로 바뀐다

장점 1) ANSI/ISO 표준 인터페이스를 준수한다 2) 응용프로그램 개발이 빠르다 3) ESQL 응용프로그램은 다른 벤더간 이식성이 좋다 단점 1) 성능이 중요시 되는 System 은 신중해야 한다 2) 응용프로그램이 복잡한 SQL interface 를 요구할 경우는 사용하는 것이 안 좋다

precompileprecompile 에서에서 nohold lock & unchained modenohold lock & unchained mode 로로 바꾸는바꾸는 옵션은옵션은??방법 1) cpre -r( nohold lock) -m (unchained mode)방법 2) ocs.cfg file 에서 CS_OPT_ISOLATION , CS_OPT_CHAINXACTS 을 정해준다

ANSI 1) chained mode 이다 2) commit 이나 rollback 을 수행해야 transaction 이 정상적으로 끝난다 3) isolation level 3 에서 수행된다

Non-ANSI unchained mode 이다 isolation level 1 을 default method 로 사용한다 자동적으로 commit 을 한다 commit 이나 rollback 을 수행해서 transaction 을 종료하고 싶으면 반드시 begin transaction 으로 trasaction 을 시작해야 한다

45

Page 46: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

Cursor Cursor 사용사용 시시 고려할고려할 점은점은?? Cursor 의 용도 선언한다 1) 용도선언 안 한다면 cursor 는 for update 로 선언된다 2) 다른 사용의 exlusive lock 을 허용 안 한다 3) read 만 할 경우는 for readonly 를 꼭 사용해야 높은 병렬성을 얻을 수 있다 4) unique index 가 있어야 index 를 효율적으로 사용할 수 있다

Array Binding 한다Fetch 시에 많은 row 를 한번에 처리하기 위해 사용

Cursor open 유지한다ANSI 는 commit 시 마다 cursor 를 close 하고 re-create 하므로 성능이 저하된다cpre -a option 을 사용하거나 ocs.cfg 에 CS_OPT_CURCLOSEONXACTS 를 false 한다

Multiple cursor 를 사용한다한 connection 위에 multiple cursor 를 open 함으로써 deadlock 을 피할 수 있다

Array BindingArray Binding 이란이란?? select into 나 fetch into 시 한번에 많은 rows 를 처리함으로써 network 부하를 많이 줄일 수 있다

nost 변수를 array 로 선언해 많은 row 를 한번에 처리한다

Datatype Datatype 호환은호환은?? 가능한 한 정의된 Datatype 을 사용한다

Character Type Behavior ImpactChar 데이타를 I/O 할 때 선언된

크기 만큼 space 를 pad함불필요하게 network packet size 가 커질 수 있음

CS_CHAR space 의 pad 없이 null terminated 됨

Network I/O높은 성능을 위해서 이 type 을 사용하는 것이 좋음

Persistent Binding Persistent Binding 이란이란??pre-compiler option 으로 불필요한 중복 binding 을 제거해주는 기능이다

-P Input Host variable 을 제어-b Output Host variable 을 제어

-b -P option 을 이용하여 프로그램 한다면 automatic variable/subscripted array 등을 주의해야 한다

Text/Image Datatype Text/Image Datatype 있다면있다면??Cpre option 에 –y 를 사용해야 한다

46

Page 47: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

CGI programCGI program 을을 위한위한 samplesample STEP 1) web server 를 시작하는 account 의 환경에 sybase환경을 잡아준다STEP 2) source sample . . main() { putenv("SYBASE=/home3/ase119/esqlc"); putenv("DSQUERY=ASE119"); putenv("LD_LIBRARY_PATH=/home3/ase119/esqlc/lib"); printf("Content-type: text/html\n"); printf("\n"); printf("<HTML>"); printf("<HEAD>"); printf("<TITLE> CGI sample program using Sybase ESQL/C</TITLE>"); printf("</HEAD>"); printf("<BR>"); printf("<H2> **** Sales 조회 **** </H2>");

EXEC SQL CONNECT :username IDENTIFIED BY :password;

EXEC SQL USE pubs2;

. . }

STEP 3) precompile makefile 로 compile 하여 실행하면 web 에서 실행이 않 됨 반드시 openclient source 를 static 으로 compile 해야 함

STEP 4) c compile : platform 별로 static compile 하는 option 이 조금씩 다르므로 주의

******* Static link and compile commands for Client-Library Platform

> > Sun Solaris 2.x> > /opt/SUNWspro/bin/cc -I$SYBASE/include -L$SYBASE/lib \> > $SYBASE/include/sybesql.c> > $SYBASE/lib/libct.a -Bstatic -lcs -ltcl -lcomn -lintl> > -Bdynamic -lnsl -ldl -lm -o program program.c> >> >> > IBM> > RS/6000> > xlc_r4 -I$SYBASE/include -L$SYBASE/lib $SYBASE/include/sybesql.c> > $SYBASE/lib/libct.a \> > -lcs -ltcl -lcomn -lintl -lm -o program program.c> >> > HP 9000(8xx)> > cc -I$SYBASE/include -L$SYBASE/lib APP_FILES -Wl,-a,archive \> > $SYBASE/lib/libct.a -lcs -ltcl -lcomn -lintl -Wl,-a,default -lcl -lm\> > -lBSD -ldld -Wl,-E,+s -o program program.c> >

47

Page 48: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

> > NCR System 3000> > cc -I$SYBASE/include -L$SYBASE/lib $SYBASE/include/sybesql.c \> > -Bstatic $SYBASE/lib/libct.a -lcs -ltcl -lcomn \> > -lintl -Bdynamic -lsocket -ldl -lnsl -lm -o program program.c> >> > SGI> > cc -o [-n32 |-n64] -mips3 -I$SYBASE/include $SYBASE/include/sybesql.c \> > -L$SYBASE/lib -Bstatic $SYBASE/lib/libct.a -lcs -ltd -lcomn \> > -lintl -Bdynamic -lm -o program program.c> >> > Digital UNIX> > cc -I$SYBASE/include -L$SYBASE/lib $SYBASE/include/sybesql.c> > $SYBASE/lib/libct.a \> > -lcs -ltcl -lcomn -lintl -lm -o program program.c> >> > SCO UnixWare> > cc -I$SYBASE/include -L$SYBASE/lib $SYBASE/include/sybesql.c -Bstatic \> > $SYBASE/lib/libct.a -lcs -ltcl -lcomn -lintl -Bdynamic \> > -lsocket -ldl -lnsl -lm -o program program.c

insertinsert 에서에서 arrayarray 변수를변수를 사용하는사용하는 예예exec sql begin declare section; int row; int int_table[3] = { 10, 20, 30, }; char *string_table[3] = { "how", "are", "you", };exec sql end declare section; for (row=0; row < 3; row++) { EXEC SQL insert into ... values (:row, :int_table[row], :string_table[row]); }

stored procedurestored procedure 를를 사용하는사용하는 법법??

EXEC SQL USE pubs2;

EXEC SQL

create procedure plus100 (@invalue int, @outvalue int out)

as

48

Page 49: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

begin

select @outvalue = @invalue + 100

end ;

exec sql exec :retstat = plus100 10, :result_value out;

printf("100 + 10 = %d \n", result_value);

imageimage 처리하는처리하는 방법은방법은??#include <stdio.h>#include "sybsqlex.h"

/* Declare the SQLCA */EXEC SQL INCLUDE sqlca; /*** Forward declarations of the error and message handlers and** other subroutines called from main().*/void error_handler();void warning_handler();#define size_i 80000 /* image 나 text 의 최대 크기 지정 */

int main(){

int i=0;

EXEC SQL BEGIN DECLARE SECTION;/* storage for login name and password */CS_CHAR username[30], password[30];CS_TEXT text_var[size_i];CS_IMAGE image_var[size_i];CS_INT max_val;

49

Page 50: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

CS_INT image_size; /* 실제 입력할 Image 크기*/EXEC SQL END DECLARE SECTION;

EXEC SQL WHENEVER SQLERROR CALL error_handler(); EXEC SQL WHENEVER SQLWARNING CALL warning_handler(); EXEC SQL WHENEVER NOT FOUND CONTINUE; /* ** Copy the user name and password defined in sybsqlex.h to ** the variables declared for them in the declare section. */

/* Connect to the server and specify the database to use */ EXEC SQL CONNECT "sa" IDENTIFIED BY "";

EXEC SQL USE tempdb ;

/* Put something interesting in the variables. */ for (i=0; i< size_i; i++ ) {

text_var[i] = '';image_var[i] = '';

} for (i=0; i< 5000; i++ ) {

text_var[i] = 'a';image_var[i] = '@';

}EXEC SQL SELECT isnull(max(index_col),0)+1.0 into :max_val from image_tab2;

if ( sqlca.sqlcode == 0 ) {

printf("Row successfully selected! \n"); }

image_size=5000; /* 실제 입력할 크기 할당 */ EXEC SQL INSERT image_tab2 VALUES(:max_val,:text_var, :image_var); if ( sqlca.sqlcode == 0 ) {

printf("Row successfully inserted! \n"); }

image_size=5000; /* 실제 UPDATE 할 크기 할당 */ EXEC SQL UPDATE image_tab2 set text_var = :text_var where index_col = 1.0; if ( sqlca.sqlcode == 0 ) {

printf("Row successfully updated! \n");}EXEC SQL SELECT text_var,image_var into :text_var,:image_var from image_tab2

where index_col = 1;

printf("Row Selected Header Info \n \n");printf("text_var => %s \n",text_var);printf("image_var => %s \n",image_var);exit(0);

}

50

Page 51: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

/*** void error_handler()** ** Displays error codes and numbers from the SQLCA and exits with** an ERREXIT status. */void error_handler(){

fprintf(stderr, "\n** SQLCODE=(%d)", sqlca.sqlcode);

if (sqlca.sqlerrm.sqlerrml){

fprintf(stderr, "\n** SQL Server Error ");fprintf(stderr, "\n** %s", sqlca.sqlerrm.sqlerrmc);

}

fprintf(stderr, "\n\n");

exit(ERREXIT);}

/*** void warning_handler()** ** Displays warning messages.*/void warning_handler(){

if (sqlca.sqlwarn[1] == 'W'){

fprintf(stderr, "\n** Data truncated.\n");

}

if (sqlca.sqlwarn[3] == 'W'){

fprintf(stderr, "\n** Insufficient host variables to store results.\n");

}return;

}

Application Name Application Name 등록방법은등록방법은??

ESQL 11.1 version 이후 부터는 runtime configuration file 인 ocs.cfg 제공되어 AP 에서 수정하는 방법을 대신하여 사용가능

Pre-compiler option 에 -x 를 사용-x 는 AP 에서 “initialize_application” 으로 씌여 졌을 때 사용한다예) cpre -x

51

Page 52: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

$SYBASE/OCS-12_0/config/sample.cfg 를 ocs.cfg 로 복사

Ocs.cfg file 에 [TEST1]항목을 만들고 다음내용을 추가한다CS_APPNAME=app_nameCS_HOSTNAME=pc_host_name

ocs.cfg 예)[ANSI_ESQL] CS_CAP_RESPONSE = CS_RES_NOSTRIPBLANKS CS_EXTRA_INF = CS_TRUE CS_ANSI_BINDS = CS_TRUE CS_OPT_ANSINULL = CS_TRUE CS_OPT_ANSIPERM = CS_TRUE CS_OPT_STR_RTRUNC = CS_TRUE CS_OPT_ARITHABORT = CS_FALSE CS_OPT_TRUNCIGNORE = CS_TRUE CS_OPT_ARITHIGNORE = CS_FALSE CS_OPT_ISOLATION = CS_OPT_LEVEL1 CS_OPT_CHAINXACTS = CS_FALSE CS_OPT_CURCLOSEONXACT = CS_TRUE CS_OPT_QUOTED_IDENT = CS_TRUE[isql][bcp][TEST1] include = ANSI_ESQL CS_APPNAME=app1 CS_HOSTNAME=pcclient

ESQL AP 에 "EXEC SQL INITIALIZE_APPLICATION APPLICATION_NAME ="TEST1 을 삽입하고 Program 을 Compile 한다예)strcpy(username, USER); strcpy(password, PASSWORD); strcpy(appname, "TEST1");

EXEC SQL INITIALIZE_APPLICATION APPLICATION_NAME = "test_1"; EXEC SQL CONNECT :username IDENTIFIED BY :password; EXEC SQL USE pubs2;

ocs.cfg file 이 생성되면 [isql],[bcp] 항목을 만들어야 ct-lib 로 만든 isql 및 bcp 을 사용가능

주요 Client-Library Properties CS_OPT_ISOLATION : transaction isolation level 을 정의 CS_OPT_CHAINXACTS : transaction mode 을 정의 CS_TRUE 이면 chained tran 을 의미함 CS_APPNAME : Application name 정의 CS_HOSTNAME : client 의 host name 을 정의

datatype datatype 호환호환

Sybase-Sup pliedTypedef

Description C Datatype SQL ServerDatatype

CS_BINARY Binary type unsigned char Binary, varbinary

52

Page 53: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

CS_VARBIN ARY Variable-length binary type None NoneCS_BIT Bit type unsigned char booleanCS_CHAR Character type char[n] char, varcharCS_VARCHAR Variable-length character type None NoneCS_ DATETIME 8-byte datetime type None datetimeCS_ DATETIME4 4-byte datetime type None smalldatetimeCS_TINYINT 1-byte integer type unsigned char tinyintCS_SMALLINT 2-byte integer type sort smalllintCS_INT 4-byte integer type long intCS_DECIMAL Decimal type None decimalCS_NUMERIC Numeric type None numericCS_FLOAT 8-byte float type double floatCS_REAL 4-byte float type float realCS_MONEY 8-byte money type None moneyCS_MONEY4 4-byte money type None smallmoneyCS_TEXT Text type -y option required unsigned char textCS_IMAGE Image type -y option required unsigned char image

2.WIN/NT2.WIN/NT NT 에서 ASE 제거를 수동으로 하려면? WIN/NT 에서 OpenClient Runtime 만 배포하려면? SYBASE Central 실행시 Unable to load language dll 'scsslgko' 나오면? NT 에서 BACKUP scheduling 은? NT 에 ASE 설치후 프로그램에 SYBASE 가 안보인다?

NTNT 에서에서 ASEASE 제거를제거를 수동으로수동으로 하려면하려면??Windows NT 에서 재설치 할 경우에는 이전에 설치된 사항을 삭제하고 하는 것이 바람직하다. 특히, 설치 중에 문제가 생겨 재설치하는 경우라면 반드시 아래의 과정을 거쳐야 한다.

53

Page 54: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

ASE 11.9 이하STEP 1) 모든 Sybase product 을 종료STEP 2) Windows NT 의 Registry editor (C:\WINNT\SYSTEM32\regedt32.exe)를 실행STEP 3) HKEY_LOCAL_MACHINE / SOFTWARE / Sybase =>삭제STEP 4) HKEY_LOCAL_MACHINE / SYSTEM / CurrentControlSet / Control / Session Manager /Environment => Sybase 관련 변수 삭제 (DSLISTEN, DSQUERY, SYBASE 등), PATH 에서 Sybase 관련 경로 삭제 (예: c:\sybase\dll;c:\sybase\bin)STEP 5) HKEY_LOCAL_MACHINE / SYSTEM / software / sybase => 삭제STEP 6) System 재시작STEP 7) 모든 Sybase directory 삭제, 시작메뉴의 Sybase 프로그램그룹 삭제STEP 8) SQL Server 재설치

ASE 12 인 경우STEP 1) ASE 를 종료한다STEP 2) NT server 를 restart 한다 (ASE 가 사용하던 DLL 을 release 하기 위해)STEP 3) regedit32 수행(From the Windows task bar, select Start | Run, then enter regedt32 for Windows NT, or regedit for Windows 95/98 to start the registry utility.)

STEP 4) Go to HKEY_LOCAL_MACHINE\SOFTWARE\Sybase\Server. \Server directory 에서 ASE 관련 모든 Key 를 delete 한다 \\HKEY_LOCAL_MACHINE\SOFTWARE\SYBASE\Server\<server_name> \\HKEY_LOCAL_MACHINE\SOFTWARE\SYBASE\Server\<server_name>_BS \\HKEY_LOCAL_MACHINE\SOFTWARE\SYBASE\Server\<server_name>_HS \\HKEY_LOCAL_MACHINE\SOFTWARE\SYBASE\Server\<server_name>_MS For the following Registry key: \\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session\Manager\Environment make these changes: ASE 의 환경변수를 지운다 DSLISTEN, DSQUERY, and SYBASE, and other Sybase-관련변수) PATH 에서 ASE 관련내용을 지운다. In the following Registry key: \\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services remove these references: SYBSOL_<server_name> SYBXPS_<server_name>_XP SYBBCK_<server_name>_BS SYBMON_<server_name>_MS SYBHIS_<server_name>_HS

Restart your computer to update the changes to the Registry.

If you get an Event Viewer warning upon restarting the computer, you may not have cleaned up all services. See the Event Viewer Application log for details.

Use the Service Control Panel to verify that the Adaptive Server service has been removed. If it has not, check the Registry for the same keys for the CurrentControlSet in ControlSet001 and ControlSet003. Make sure you have deleted the specified entries from the Registry.

Delete the master device and system procedure device files from the Sybase installation directory (the default is \sybase\data).

54

Page 55: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

Reinstall Adaptive Server as a new server.To Remove an Old Server:

Stop the server. See Chapter 11, "Starting and Stopping Servers" for more information.

Reboot the machine to release any DLLs.From the Windows Task bar, click Start | Programs | Sybase | Server Config.The Configure Sybase Server window displays.Click Help in any window to read detailed information about uninstallation. Click Contents to view available topics. Click Close or Minimize Help to return to the installation program.Select the type of Sybase server you want to remove from the icons on the left of the Configure Sybase Servers screen.Click Remove Adaptive Server. This displays an Existing Servers window.Select the server you want to remove, and click OK.Remove the following entries from the Registry key \\HKEY-LOCAL-MACHINE\SYSTEM\CurrentControlSet\Services:SYBBCK-*SYBHIS-*SYBMON-*SYBSQL-*SYBXPS-*

Reboot the computer to reset registry entries.The installation program does not delete shared dynamic link libraries (DLLs), such as libunic.dll, mchelp.dll, and mclib.dll, from the Windows system directory. Remove these files manually.If you do an overlay install, the installation program does not allow you to create servers that already exist in CurrentControlSet. If you want to use the same name, you must also clear the server names from the Registry and then restart the computer.

WIN/NTWIN/NT 에서에서 OpenClient RuntimeOpenClient Runtime 만만 배포하려면배포하려면??

11.1.1 open client 32 bit

Non Developement files needed:

Subdirectory files************ ******BIN If you plan on using: dsedit bcp isql defncopy.exe ocscfg.exe You must keep: ocscfg.dat(ocscfg.exe is the editor) wsybset.bat

INI sql.ini libctl.cfg mnemonic.dat objectid.dat

55

Page 56: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

LOCALES locales.dat||__ ENGLISH Keep english lang. subdirectory and the | required charset subdir, and all files below it. | |__<charset>> Example: I want to use cp850 so I would keep the \sybase\locales\english\cp850 directory -MESSAGES keep all subdirectory under here message/<LANGUAGE_NAME> such as 'us_english' and delete the rest.

CHARSETS keep utf8 subdirectory and other charset directory that you need and all files below it Example: I want to use cp850 so I would keep this directory and delete the others like MAC..ROMAN8 etc

DLL please keep the following files: LIBCOMN.DLL LIBCS.DLL LIBCT.DLL LIBINTL.DLL LIBSYBDB.DLL LIBTCL.DLL LIBBLK.DLL libdce.dll libintl.dll libdreg.dll libsmssp.dll Net Libs NLMSNMP.DLL (Named Pipes) NLWNSCK.DLL (TCP/IP) ( Optional depending on install options ) NLNWLINK.DLL spx NLDECNET.DLL decnet (This dll is different for 95 and NT) NLNWADVT.EXE spx(This is not needed but apply latest ebf)

#Note : on 95 the dlls are in the /windows/system directory on NT the dlls are in the SYBASE/dll directory.

Directories not needed for a non developer/runtime

LibIncludeinstallbin (unless use want to use isql,bcp)Sample

The next thing is related to REGEDIT values:You should add the following to your 95 registry -

56

Page 57: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

> [HKEY_LOCAL_MACHINE\SOFTWARE\SYBASE]>>

> Actual entries:>[HKEY_LOCAL_MACHINE\SOFTWARE\SYBASE\open client]Note for this key there are string value entries:

Value nameValue data

(Defalut) <-- leave this blank

InstallDate 5-28-1997

[HKEY_LOCAL_MACHINE\SOFTWARE\SYBASE\setup\sybaseNote for this key there are string value entries:

Value nameValue data

(Defalut) <-- leave this blank

SYBASE C:\SYBASE

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\

For .exe if you use themdseditocscfg.exe

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App =Paths\dsedit.exe

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App =Paths\ocscfg.exe

Note two string value entries:

# Note : on NT dlls are in the sybase/dll on 95 dlls are in the windows/system

SYBASE Central SYBASE Central 실행시실행시 Unable to load language dll 'scsslgko'Unable to load language dll 'scsslgko' 나오면나오면??아래 error 가 나오고 Central 이 실행되지 않는다면Unable to load language dll 'scsslgko'Could not even load default language dll.

C:\sybtools\asep>copy scsslgen.dll scsslgko.dll 위 file 을 copy 해 놓으므로써 해결됨

NTNT 에서에서 BACKUP schedulingBACKUP scheduling 은은?? scheduling 하는 방법은 2 가지가 있습니다

57

Page 58: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

방법 1) NT 스케줄러의 GUI 를 이용한다 NT 스케줄러 ICON 을 더블클릭 -> Add 버튼을 클릭 -> backup.bat 의 fullpath 입력 -> 원하는 시간을 SET 한다

방법 2) NT 스케줄러 command 로 이용한다 도스 command line 에서 at 14:54 "c:\bckup.bat"

일반적으로 NT 에서 BACKUP TAPE 장비는 '\\.\tape0' 이다

NTNT 에에 ASEASE 설치후설치후 프로그램에프로그램에 SYBASESYBASE 가가 안보인다안보인다??맞습니다. 이것은 개선해야 하는 점입니다.현재 Start Menu -> Programs 에 위치하고 있다

3.이름변경 (db,dbo,table 명)

4.MISC 4.MISC ASE 가 사용하는 reserved word 아는 방법? system function ? rule 과 rule 에 bind 된 column 을 볼 수 있는가? table 과 index 를 list 해서 볼 수 있는가? table 에 reserved 된 영역이 얼마인지 list 해서 볼 수 있는가? table 이 실제 사용하는 size 를 list 해서 볼 수 있는가?

58

Page 59: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

ASEASE 가가 사용하는사용하는 reserved wordreserved word 아는아는 방법방법??1> select name from spt_values where type = "W"2> go

system functionsystem functionhost_id() : client process 의 현재의 호스트 프로세스 IDhost_name() :client process 의 현재의 host compure namesuser_id ("login_name") : ASE 의 login idsuser_id ("login_id") : ASE 의 login nameuser_id("name_in_db") : database 내에서 user iduser_id("id_in_db") : database 내에서 user nameshow_role() : user 의 현재 roledb_id("db_name") : db 의 iddb_name(db_id) : db 의 nameobject_id("objname") : object 의 idobject_name(obj_id) : object 의 namecol_name(obj_id,col_Id) : column namecol_length("objname","colname") : column lengthindex_col("objname",index_id,key#) : index columndatalength(expression) expression 의 길이

rulerule 과과 rulerule 에에 bindbind 된된 column column 을을 볼볼 수수 있는가있는가??1> select sysobjects.name+' '+ object_name(syscolumns.id)+'.'+ syscolumns.name2> rule_table_and_col_bound_to3> from sysobjects, syscolumns4> where object_name(syscolumns.domain)=sysobjects.name and sysobjects.type = R''5> go

rule_table_and_col_bound_to

-----------------------------------------------------------------------

pub_idrule publishers.pub_id

title_idrule salesdetail.title_id

title_idrule titles.title_id

59

Page 60: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

table table 과과 index index 를를 listlist 해서해서 볼볼 수수 있는가있는가??1> select object_name(o.id), i.name2> from sysindexes i, sysobjects o3> where i.id = o.id and o.type = "U"4> and i.indid > 0 and i.indid < 2555> order by o.id6> go name ------------------------------ ------------------------------ authors auidind authors aunmind publishers pubind roysched titleidind sales salesind salesdetail titleidind salesdetail salesdetailind titleauthor taind titleauthor auidind titleauthor titleidind titles titleidind titles titleind

tabletable 에에 reservedreserved 된된 영역이영역이 얼마인지얼마인지 listlist 해서해서 볼볼 수수 있는가있는가??1> create procedure reserved_xyz as2> drop table #temporary3>4> select o.name, o.uid, i.indid, reserved_pgs(i.id,doampg) as "size"5> into #temporary6> from sysindexes i, sysobjects o7> where i.id = o.id and i.indid <= 18>9> insert #temporary10> select o.name, o.uid, i.indid, reserved_pgs(i.id,ioampg) as "size"11> from sysindexes i, sysobjects o12> where i.id = o.id and i.indid > 113>14> select user_name(uid) as "owner", name, sum(size) *215> as "size (kb)"16> from #temporary17> group by uid, name18>19> drop table #temporary20> return21> goowner name size (kb) ------------------------------ ------------------------------ -----------dbo app_dis 16 dbo au_pix 32 dbo authors 32 dbo blurbs 32 dbo child_tab 16

60

Page 61: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

tabletable 이이 실제실제 사용하는사용하는 sizesize 를를 listlist 해서해서 볼볼 수수 있는가있는가??1> create procedure used_xyz as2> drop table #temporary3>4> select o.name, o.uid, i.indid, used_pgs(i.id,doampg,ioampg) as "size"5> into #temporary6> from sysindexes i, sysobjects o7> where i.id = o.id8>9> select user_name(uid) as "owner", name, sum(size) *2 as "size (kb)"10> from #temporary11> group by uid, name12>13> drop table #temporary14> return15> goowner name size (kb) ------------------------------ ------------------------------ ----------- dbo app_dis 4 dbo au_pix 8 dbo authors 12 dbo blurbs 20 dbo child_tab 4 dbo discounts 4 dbo parent_tab 4 dbo publishers 8 dbo roysched 10 dbo sales 8 dbo salesdetail 24 dbo stores 4

5.password 관련

6.ASE 관리기본

7.DBA , 7.DBA , 이것은 꼭이것은 꼭

61

Page 62: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

backup 관련 ASE 작업시 문제발생시

backup backup 관련관련 backup 을 주기적으로 하는 것은 중요한 일입니다

더 중요한 것은 backup 받은 것을 load 해 보는 것입니다

현재 선택한 backup 전략으로 손실가능한 data 를 상상해 본다예를 들면, 저녁마다 full backup 받는다면 오후 3 시경에 문제발생시 9 시~3 시 까지는 잃을 수 있다. 이를 허용하는가? 등등을 상상해 본다

product backup 도 중요하다ASE 설치된 disk 가 문제를 일으킬 수도 있다현재 설치된 ASE 와 EBF 의 backup 과 version 이 얼마인지는 알고 있어야 한다

dump 로 backup 받기 이전에 database consistency 를 check 한다dbcc checkdb,dbcc checkcatalog,dbcc checkalloc 을 수행해 문제없음을 확인한다

server 의 환경 file 도 backup 받는다ASE 명.cfg 와 interfaces 와 locales.dat 등도 받아두면 좋습니다

ddl script backup 도 중요하다database 를 새롭게 만들어야 하는 경우에 필수적이다

중요 system db 를 받는다master – 필수적이다model – 기본을 변경하였을 경우는 backup 받는다

user db 를 받는다

가장 필수적인 것은 master, user db 를 dump 받는 것이다

ASEASE 작업시작업시 backup 을 받아 놓고 시작한다

작업중간에 다른 user 의 connection 이 없게 한다 dataserver 를 single mode 로 한다 (RUN_ 파일에 -m 옵션을 추가한다)

평소에 DISK공간을 확보하는 것이 도움이 많이 된다만약 1 TABLE 만 BACKUP 받은 곳에서 내리고 싶다면, 아직까지 ASE 는 DB 단위로 밖에 LOAD가 안되므로 전체 DB 를 LOAD 한뒤, TABLE 을 받아내는 수 밖에 없다결국에 LOAD 할 영역을 확보해 놔야 한다는 얘기가 된다

현재 disk 의 어느 부분을 어떻게 할당해서 사용하고 있는지를 그림으로 갖고 있는 것이 편하다

62

Page 63: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

문제문제 발생시발생시 항상 errorlog 를 먼저 본다

현상황을 적어가며 정리해 보는 것이 많이 도움된다 RC 에 연락하실 때는 현재 사용하는 version 과 platform version 그리고 ebf 등을 꼭 넣으 시고 현상황을 정리한 내용과 errorlog 를 주면 빠르게 대처하기 쉽다

ADMIN -3 (database,dump/load,log,dbcc 관련)

63

Page 64: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

1.create / alter database1.create / alter database Syntax Create database 과정에서 일어나는 작업은? 기존에 backup 받은 경우, 빠르게 DB 만드는 방법? LOG 분리하는 이유? DB 의 최소,최대 SIZE 는? DATA 와 LOG 의 비율은? Alter database 할때, size 는 추가 size냐? 총 size냐? Alter database 한뒤, shutdown 해야 효력이 있는가? with override 옵션은 언제쓰는가?

SyntaxSyntax create database database_name

[on {default | database_device} [= size] [, database_device [= size]]...] [log on database_device [= size] [, database_device [= size]]...] [with override] [with default_location = "pathname"] [for proxy_update] [for load]

kordb 라는 12M 데이터베이스를 만든다8M 는 데이터부분을 위해 할당하고, 4M 는 트랜재션 로그를 위해 할당된다1> create database kordb2> on data_device_1=83> log on log_device_6=44> go

alter database - Increases the amount of space allocated to a database alter database database_name [on {default | database_device } [= size] [, database_device [= size]]...] [log on { default | database_device } [ = size ] [ , database_device [= size]]...] [with override] [for load]

tempdb 에 10mega 를 추가한다alter database tempdb on temp_dev = 10

Create database Create database 과정에서과정에서 일어나는일어나는 작업은작업은??DB 를 만들때 서버는 다음과 같은 일들을 한다.STEP 1) Database space 할당한다STEP 2) Database 를 위한 sysdatabase 에 한 행을 삽입한다

64

Page 65: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

STEP 3) 각 장치 플래그먼트마다 sysusage 에 한 행 삽입한다.STEP 4) 각 영역(extent)을 8 데이터 페이지로 구성한다STEP 5) Model 데이터베이스를 새 데이터베이스에 복사한다

기존에기존에 backup backup 받은받은 경우경우, , 빠르게빠르게 DBDB 만드는만드는 방법은방법은??for load 옵션을 사용한다. create database DB_NAME on…… for load

데이터베이스 페이지를 초기화하는 만큼의 시간을 줄일 수 있다.

LOGLOG 분리하는분리하는 이유는이유는?? recovery 를 위한 것이다 실제로 log 는 write 가 많이 일어나므로 별도의 영역을 주는 것이 좋다 incremental backup 을 받을 수 있다

DBDB 의의 최소최소, , 최대최대 SIZE SIZE 는는?? 최소 size 는 model db 의 크기이다 최대 size 는 32 * 255 giga 이다(현재 device 의 최대 size 는 32giga 이고, 사용할 수 있는 fragment 의 최대수는 255 이므로)

DATADATA 와와 LOGLOG 의의 비율은비율은 ??사실 data 와 log 의 비율을 고려하지는 않는다

보통은 log 를 data 의 20 %를 많이 사용한다그러나 , log 를 좌우하는 것은 dump tran 으로 얼마나 자주 log 를 자주 비워주는 지와 실제 log에 기록되는 작업이 얼마나 자주 또 얼마나 많은 양인지에 따라 다른 것이다

Alter databaseAlter database 할할 때때, size, size 는는 추가추가 sizesize냐냐? ? 총총 sizesize냐냐??추가 size 이다

Alter databaseAlter database 한한 뒤뒤, shutdown, shutdown 해야해야 효력이효력이 있는가있는가??아닙니다. 즉시 효력 있다

with override with override 옵션은옵션은 언제쓰는가언제쓰는가??같은 device 에 data 와 log 를 같이 쓰는 경우에 사용한다. 추천되지 않는다

1> create database user_db on dev1=1, dev1=12> log on dev1=13> goCREATE DATABASE: allocating 512 pages on disk 'dev1'CREATE DATABASE: allocating 512 pages on disk 'dev1'Msg 1820, Level 16, State 1:Line 1:This command adds log space to disk 'dev1', which previously contained onlydata. You must specify WITH OVERRIDE to force this allocation.

1> create database user_db on dev1=1, dev1=12> log on dev1=1 with override3>4> go

65

Page 66: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

CREATE DATABASE: allocating 512 pages on disk 'dev1'CREATE DATABASE: allocating 512 pages on disk 'dev1'CREATE DATABASE: allocating 512 pages on disk 'dev1'Caution: You have set up this database to include space on disk 20 for bothdata and the transaction log. This can make recovery impossible if that diskfails

66

Page 67: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

2.dump database2.dump database Syntax tape 에 받을때, capacity 를 꼭 사용해야 하는가? 1 개의 DB 를 동시에 여러 TAPE(DISK)에 받고 싶다 1 개의 DB 를 순차적으로 여러 TAPE(DISK)에 받고 싶다 1 개의 TAPE 에 여러 개의 DB 를 받고 싶다 Remote Backup Server 를 사용해 Backup 하는 방법은? incremental backup 은?

SyntaxSyntaxDump database 로 백업한 데이터베이스를 복구하는 명령어이다

dump database database_name to stripe_device [ at backup_server_name ] [density = density_value, blocksize = number_bytes, capacity = number_kilobytes, dumpvolume = volume_name, file = file_name] [stripe on stripe_device [ at backup_server_name ] [density = density_value, blocksize = number_bytes, capacity = number_kilobytes, dumpvolume = volume_name, file = file_name]] [[stripe on stripe_device [ at backup_server_name ] [density = density_value, blocksize = number_bytes, capacity = number_kilobytes, dumpvolume = volume_name, file = file_name]]...] [with { density = density_value, blocksize = number_bytes, capacity = number_kilobytes, dumpvolume = volume_name, file = file_name, [dismount | nodismount], [nounload | unload], retaindays = number_days, [noinit | init], notify = {client | operator_console} }]

tapetape 에에 받을때받을때, capacity, capacity 를를 꼭꼭 사용해야사용해야 하는가하는가??꼭 사용해야 한다. capacity 는 tape 의 용량을 말하는 것이다tape 의 full 용량보다는 70 ~ 80%를 정하는 것이 좋다

11 개의개의 DBDB 를를 동시에동시에 여러여러 TAPE(DISK)TAPE(DISK)에에 받고받고 싶다싶다stripe on 을 사용한다

tape1, tape2, tape3 에 동시에 dump 를 받는다. 거의 backup 받는 양의 1/3 정도씩 나눠

67

Page 68: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

서 받친다

dump database db 명 to '/dev/tape1' stripe on '/dev/tape2' stripe on '/dev/tape3'

11 개의개의 DBDB 를를 순차적으로순차적으로 여러여러 TAPE(DISK)TAPE(DISK)에에 받고받고 싶다싶다sp_volchanged session_id, devname, action [, fname [, vname]]

dump database 로 해당 db 를 backup 받다가 tape 의 capacity 를 넘어서면 sp_volchanged하라는 message 가 나온다. 이때 나오는 session_id 를 기억했다가, 다른 곳에서 isql 로 접속하여, session_id 를 넣고,devname 을 넣고, action 에는 proceed 를 넣어 그 다음 tape 에서 연결해서 받도록 한다

11 개의개의 TAPETAPE 에에 여러여러 개의개의 DBDB 를를 받고받고 싶다싶다dump 명령문에 option 을 주어서 받는다 with init 은 처음인 경우로 tape 을 initialize 한다dump database db1 to "/dev/tape1" with init

다음 db2 를 받는다dump database db2 to "/dev/tape1"

마지막으로 db2 를 받는다option with unload 는 tape 을 앞으로 감고 mount 를 내린다dump database db3 to "/dev/tape1" with unload

Remote Backup ServerRemote Backup Server 를를 사용해사용해 BACKUP BACKUP 하는하는 방법방법local Backup Server 가 start 되어 있어야 한다dump … to at 다음에 Remote Backup Serer 를 명시해야 한다

ASE 의 local Backup Server 는 항상 이름이 SYB_BACKUP 이다sp_helpserver 로 확인해야 한다

아래의 예에서는 SYB_BACKUP 이 실제로 Physical 하게는 Interface 상에서 ASE119_back 으로 나오고 있음을 의미한다1> sp_helpserver2> go name network_name class status id ------------------------------ ------------------------------ --------------- ----------------------------------------------------------------------- ----- SYB_BACKUP ASE119_back ASEnterprise timeouts, no net password encryption, writable , rpc security model A 4

1> dump database DB_NAME

68

Page 69: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

2> to "/dev/nrmt4" at REMOTE_BKP_SERVER3> stripe on "/dev/nrmt5" at REMOTE_BKP_SERVER4> go

REMOTE_BKP_SERVER 는 sp_helpserver 로 확인한다

incremental backupincremental backup 은은??dump tran 으로 받는다

69

Page 70: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

3.load database3.load database Syntax Multi-Volumn(동시에 1DB 를 여러 TAPE 에 DUMP)를 LOAD 하는 방법은? Multi-File (여러 DB 를 1 개 TAPE 에 DUMP)에서 LOAD 하는 방법은? Remote Backup Server 를 사용해 LOAD 하는 방법은? OPTION (with dismount | nodismount) (with nounload | unload) Msg 8009 가 발생하면? 사용 중이어도 LOAD 할 수 있는가? 'Data on dump will not fit into current database' 가 발생하면? dump 받은 DB 명과 load 하는 DB 명이 달라도 되는가? Msg 950 발생하면? 다른 기종에서 BACKUP 된 내용이 LOAD 될 수 있는가? 다른 Version 의 BACKUP 된 내용을 LOAD 할 수 있는가? TABLE 별로 LOAD 될 수 있는가? Sybmultibuf 란 ?

SyntaxSyntaxDump database 로 백업한 데이터베이스를 복구하는 명령어이다

load database database_name from stripe_device [at backup_server_name ] [density = density_value, blocksize = number_bytes, dumpvolume = volume_name, file = file_name] [stripe on stripe_device [at backup_server_name ] [density = density_value, blocksize = number_bytes, dumpvolume = volume_name, file = file_name] [with { density = density_value, blocksize = number_bytes, dumpvolume = volume_name, file = file_name, [dismount | nodismount], [nounload | unload], listonly [= full], headeronly, notify = {client | operator_console} }]]

Multi-Volumn(Multi-Volumn(동시에동시에 1DB1DB 를를 여러여러 TAPETAPE 에에 DUMP)DUMP)를를 LOADLOAD 하는하는 방법은방법은??1> load database pubs2 from "/dev/nrmt0"2> stripe on "d:\backups\backup2.dat"3> stripe on "d:\backups\backup3.dat"4> go

Multi-File (Multi-File (여러여러 DBDB 를를 11 개개 TAPETAPE 에에 DUMP)DUMP)에서에서 LOADLOAD 하는하는 방법은방법은??dump volume 을 알고 있다면 load 명령시 from 절에 적어주면 된다

70

Page 71: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

dump volume 을 모른다면 load 명령시 "with listonly"을 사용하여 dump volume 을 확인후 load하면 된다

71

Page 72: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

Remote Backup ServerRemote Backup Server 를를 사용해사용해 LOAD LOAD 하는하는 방법은방법은??1> load database pubs22> from "/dev/nrmt4" at REMOTE_BKP_SERVER3> stripe on "/dev/nrmt5" at REMOTE_BKP_SERVER4> stripe on "/dev/nrmt0" at REMOTE_BKP_SERVER5> go

REMOTE_BKP_SERVER 는 sp_helpserver 로 확인한다

OPTION (with dismount | nodismount) (with nounload | unload) OPTION (with dismount | nodismount) (with nounload | unload) OPTION 설명 dismount | nodismount :Tape 장치 사용 시 load 후에 tape 장치의 mount 유지여부를 설정한다 nounload | unload : Tape 장치 사용 시 load 후 tape rewind 여부를 설정한다

Msg 8009Msg 8009 가가 발생하면발생하면??LOAD 시, 작업할 DB 는 존재해야 한다

사용중이어도사용중이어도 LOADLOAD 할할 수수 있는가있는가??LOAD 시, 작업하는 DB 는 사용중인 사람이 없어야 한다

'Data on dump will not fit into current database' 'Data on dump will not fit into current database' 가가 발생하면발생하면??LOAD 시, BACKUP 받은 DB 보다 크기가 크거나 같아야 한다

dumpdump 받은받은 DBDB 명과명과 loadload 하는하는 DBDB 명이명이 달라도달라도 되는가되는가??LOAD 시, 작업하는 DB 은 BACKUP 받은 DB 명과 달라도 된다

Msg 950Msg 950 발생하면발생하면??LOAD 후, 반드시 online 명령어를 수행해야 한다Online database <db_name>

72

Page 73: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

다른다른 기종에서기종에서 BACKUPBACKUP 된된 내용이내용이 LOADLOAD 될될 수수 있는가있는가? ? 불가하다

다른다른 Version Version 의의 BACKUPBACKUP 된된 내용을내용을 LOADLOAD 할할 수수 있는가있는가??상위버전 dump 하위버전 load : 불가하위버전 dump 상위버전 load : 가능

TABLETABLE 별로별로 LOADLOAD 될될 수수 있는가있는가??일반적인 load 명령을 사용할 수는 없고 table 별 작업은 bcp utility 를 사용한다

Sybmultibuf Sybmultibuf 란란 ??Dump 시에 dumping data 가 일시적으로 머무르게 되는 buffer 를 말한다"ps -ef | grep sybmultibuf"를 써서 buffer 내용 유무를 알 수 있다

73

Page 74: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

4.db option4.db option Syntax DB 에 log suspend 가 안걸리게 하고 싶은 경우는? TRANSACTION 안에서 CREATE TABLE 을 하고싶은 경우는? SELECT INTO 를 사용하거나 BCP IN 을 하고 싶은 경우는? DUMP TRAN 을 자동적으로 하게 하고 싶은 경우는? SINGLE USER 상태로 하고 싶은 경우는? 그 밖의 OPTION 들은?

SyntaxSyntax사용자 데이터베이스를 생성한 후 업무 내용에 따라 필요한 option 을 하여 데이터베이스의 기능을 확장하여 사용할 수 있다

sp_dboption [ dbname, optname,{true|false}]

dbname - option 을 적용하고자 하는 DB 명 master database 에서만 db option 을 변경하거나 설정하는 것이 가능하다 optname - 적용 또는 해제하려는 option 을 정의 {true/false} - true : Option 을 적용하려면 true 로 설정 false : option 을 해제하려면 false 로 설정한다 use mastergosp_dboption pubs2 , ' select into/bulkcopy/pllsort' , truego

Database option 'select into/bulkcopy/pllsort' turned ON for database 'pubs2'.Run the CHECKPOINT command in the database that was changed.(return status = 0)

use pubs2gocheckpointgo

DBDB 에에 log suspendlog suspend 가가 안걸리게안걸리게 하고하고 싶은싶은 경우는경우는??'abort tran on log full' option 을 사용하면 된다

TRANSACTION TRANSACTION 안에서안에서 CREATE TABLECREATE TABLE 을을 하고하고 싶은싶은 경우는경우는??' ddl in tran' option 을 사용하면 된다

1> begin tran2> go1> create table ABC ( col1 int )2> goMsg 2762, Level 16, State 3:Server 'ASE12A', Line 1:The 'CREATE TABLE' command is not allowed within a multi-statement transactionin the 'pubs2_new' database.

74

Page 75: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

SELECT INTO SELECT INTO 를를 사용하거나사용하거나 BCP INBCP IN 을을 하고하고 싶은싶은 경우는경우는??' select into/bulkcopy/pllsort' option 을 사용하면 된다1> select * into authors_copy from authors2> goMsg 268, Level 16, State 2:Server 'ASE12A', Line 1:You can't run SELECT INTO in this database. Please check with the DatabaseOwner.

DUMP TRANDUMP TRAN 을을 자동적으로자동적으로 하게하게 하고하고 싶은싶은 경우는경우는??' trunc log on chkpt' option 을 사용하면 된다checkpoint 가 발생할 때마다 메모리의 dirty data page 와 log page 가 database device 또는 log device 에 적용된다checkpoint 가 기동하면 데이터에 대한 integrity 가 보장된다는 가정하에 log segment 를 truncate시켜 log segment 가 full 되지 않도록 log segment 를 관리한다이 경우 incremental backup 이 이루어 지지 않으므로 up-to-the-minute 복구나 point-in-time 복구를 할 수 없고 full backup 에만 의존하게 되므로 주의해야 한다

SINGLE USER SINGLE USER 상태로상태로 하고하고 싶은싶은 경우는경우는??' single user' option 을 사용하면 된다1> dbcc checkalloc(pubs2_new,fix)2> goChecking pubs2_newMsg 2595, Level 16, State 2:Server 'ASE12A', Line 1:Database 'pubs2_new' must be set to single user mode before executing thiscommand.DBCC execution completed. If DBCC printed error messages, contact a user withSystem Administrator (SA) role.

그그 밖의밖의 OPTIONOPTION 들은들은?? allow nulls by defaultASE 에서 table 생성시 각 컬럼의 default property 는 not null 이다이 옵션이 지정되면 컬럼의 default property 는 null 이 된다ANSI 표준의 Default property 가 null 이므로 다른 DB 로부터의 Migration 등을 적용할 때 유용하게 사용할 수 있을 것 같다

Dbo use onlyDB 를 사용하는 사용자를 제한하기 위해 사용할 수 있다이 옵션이 지정된 DB 는 단지 dbo 만이 사용할 수 있다

DDL(data definition language: create/alter/drop/truncate/rename)

Auto identityAuto identity 옵션이 지정된 DB 에 테이블을 생성하면 자동으로 10-digit identity column 이 부여된다

Read onlyRead only 옵션이 지정된 DB 는 어떤 변경도 허용이 안되며 검색만이 가능하다create/drop/truncate/rename/delete/update/grant/revoke 등을 사용할 수 없다

75

Page 76: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

No free space acctgNon-log 세그먼트에 대한 free space 의 계산 또는 threshold action 을 억제한다이 옵션은 recovery time 을 빠르게 해준다

no chkpt on recoveryrecovery 동안 트랜잭션 로그에 checkpoint record 를 기록하지 않는다

76

Page 77: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

5.logsegment 5.logsegment database 생성뒤, logsegment 분리하는 방법은? logsegment 를 datasegment 로 바꾸는 방법은? sp_thresholdaction 을 이용해 logsegment full 을 방지하는 방법은? sp_dboption 을 이용해 logsegment full 을 방지하는 방법은?

databasedatabase 생성뒤생성뒤, logsegment , logsegment 분리하는분리하는 방법방법sp_logdevice 를 이용한다

STEP 1) dump tran db 명 with truncate_onlySTEP 2) alter database db 명 log on device 명 = n ( n : mega 단위)STEP 3) sp_logdevice db 명, device 명

logsegmentlogsegment 를를 datasegmentdatasegment 로로 바꾸는바꾸는 방법방법

다음과 같이 user_db 를 dev1 에 data 와 log 를 같이 쓰게했다1> create database user_db on dev1=1, dev1=12> log on dev1=1 with override3>4> goCREATE DATABASE: allocating 512 pages on disk 'dev1'CREATE DATABASE: allocating 512 pages on disk 'dev1'CREATE DATABASE: allocating 512 pages on disk 'dev1'Caution: You have set up this database to include space on disk 20 for bothdata and the transaction log. This can make recovery impossible if that diskfails

그런 다음 log 부분에 dev2 을 20M 로 추가 하였다.1> alter database user_db log on dev2 = 12> goExtending database by 512 pages on disk dev2Warning: Using ALTER DATABASE to extend the log segment will cause userthresholds on the log segment within 128 pages of the last chance threshold tobe disabled.

sysusages table 을 보면 다음과 같다: 1> select * from sysusages where dbid = db_id("user_db")2> go dbid segmap lstart size vstart pad unreservedpgs ------ ----------- ----------- ----------- ----------- ------ ------------- 4 3 0 512 335544320 NULL 0 4 3 512 512 335544832 NULL 391 4 4 1024 512 335545344 NULL 510 4 4 1536 512 352321536 NULL 512

dev1 의 log segment 부분을 data segment 로 변경 하고자 할 때 방법을 사용한다

STEP 1) dev1 의 log segment 을 off 한다1> use user_db2> go

77

Page 78: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

1> sp_dropsegment "logsegment", user_db, dev12> go

STEP 2)log 로 사용되던 dev1 에 system 과 default segment 을 추가한다1> use user_db2> go1> sp_extendsegment 'system', user_db, dev12> go1> sp_extendsegment 'default', user_db, dev12> go

STEP 3) 현재 log 의 위치를 본다1> dbcc dbinfo(user_db)2> go

DBINFO STRUCTURE:

offset 0=dbi_lastlr: (136,0)offset 8=dbi_dpbegxact: (1030,1) user_db 의 logical page# 1030 은 dev1 부분이다

STEP 4) log 가 logical page# (512*3)번 이상이어야 dev2 를 사용하는 것이므로 dummy_tbl 을 만들어 옮겨가게 한다1> create table dummy_tbl ( a char(255), b char(255))2> go1> insert dummy_tbl values('a','b')2> go 100(1 row affected)100 xacts:

STEP 5) dump tran 한뒤, 현재 log 의 위치를 본다1> dump tran user_db with truncate_only2> go1> dbcc dbinfo(user_db)2> go

DBINFO STRUCTURE:

offset 0=dbi_lastlr: (136,0)offset 8=dbi_dpbegxact: (1698,2) 현재 dev2 로 log 가 옮겨간 것을 확인했다

sp_thresholdactionsp_thresholdaction 을을 이용해이용해 logsegment fulllogsegment full 을을 방지하는방지하는 방법은방법은??log 영역에 last-chance threshold 지점이 생성된다. 이 지점을 경과해서 기록되면 SQL Server 는 sp_thresholdaction 이라는 이름의 stored procedure 를 수행한다. 따라서 dump tran 을 수행하는 내용의 sp_thresholdaction 을 만들어놓으면 log full 이 발생하는 것을 방지할 수 있다

Transaction log last-chance threshold

78

Page 79: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

Space Used Free Space

user transactoin 이 기록되는 방향 다음은 transaction log 를 truncate 하는 내용의 예다. sp_thresholdaction 은 4 개의 parameter 를 갖고있으며 as 이하는 임의로 구현할 수 있다

create procedure sp_thresholdaction@dbname varchar(30),@segmentname varchar(30),@space_left int,@status intas dump tran @dbname with truncate_only print "Transaction of database '%1!' was dumped.", @dbnamereturn

위의 sp_thresholdaction 이 실행되면 print 명령어의 내용이 SQL Server 의 errorlog file 에 기록된다 00:97/04/29 13:44:10.46 server: Transaction of database 'bok' was dumped.

Transaction log 를 tape 에 backup 할 경우에는 dump 명령어를 다음과 같이 하고 이 때 반드시 tape drive 에 tape 이 있어야 된다 dump tran @dbname to 'tape_device_name'

이 procedure 가 없는 경우에는 user transaction 이 last-chance threshold 지점을 경과한 뒤 기록될 때 sp_threaholdaction 이 없다는 message 가 SQL Server 의 errorlog file 에 기록된다 00:97/04/29 13:27:45.10 server Error: 2812, Severity: 16, State: 5 00:97/04/29 13:27:45.12 server Stored procedure 'sp_thresholdaction' not found. Specify owner.objectname or use sp_help to check whether the object exists (sp_help may produce lots of output)

79

Page 80: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

sp_dboptionsp_dboption 을을 이용해이용해 logsegment fulllogsegment full 을을 방지하는방지하는 방법은방법은??sp_dboption 에서 "trunc log on chkpt" 을 true 로 한다

각 db 에 checkpoint 할때마다 dump tran .. with truncate 가 수행되게 한다

80

Page 81: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

6.log suspend 6.log suspend 어떤 Transaction 이 LOG SUSPEND 걸리는가 ? log suspend 를 해결할 수 있는 방법은 ? log suspend 를 막을 수 있는 방법은 ?

어떤어떤 TransactionTransaction 이이 LOG SUSPEND LOG SUSPEND 걸리는가걸리는가 ??master 를 비롯한 모든 database 는 last-chance threshold 라는 threshold 가 있어서 만약 log segment 중에 used space 가 이 지점을 지나면 transaction log 를 dump 해야함

어느 한 transaction 이 log 를 기록하는 도중에 log segment 가 full 상태가 되면 다른 transaction이 log 를 write 하지 못하게 되면서 suspending 상태 발생

transaction log 가 lct 에 도달하게 되면, T1, T4 가 suspend 상태가 된다. 왜냐하면, T1 과 T4 는 계속되는 log 를 위한 space 를 만드는 반면, T2 와 T3 는 T1 으로 인해 dump 되지 못하므로 log는 full 상태로 진행된다. 따라서, T1 을 중지시킴으로써 T2 와 T3 를 dump 시켜서 log 의 free space 를 확보해야 한다

log suspendlog suspend 를를 해결할해결할 수수 있는있는 방법은방법은??방법 1) log 영역을 늘려준다alter database DB 명 log on DEVICE 명 = n (n : 숫자, mega 단위)

방법 2) 진행중인 task 를 없애고 ,더 이상 필요없는 log 영역을 잘라낸다

STEP 1) transaction log 에서 last chance threshold 에 도달한 transaction 을 terminate 시킨다. 1>select dbid, spid from syslogshold2>where dbid = db_id ("logsuspend 된 DB 명")3> godbid spid ------ ------

STEP 2) 위에서 찾은 spid 를 없앤다lct_admin("abort", {process_id [, database_id]})process_id 는 위에서 찾은 spid 를 넣는다database_id 는 select db_id("문제의 DB")해서 찾아낸다

STEP 3) dump tran DB 명 with truncate_only

log suspendlog suspend 를를 막을막을 수수 있는있는 방법은방법은 ?? sp_dboption 으로 해당 db 에 "abort tran log full"을 setting 한다

81

T1 T

2 T3 T

4

lct

Transaction log

Page 82: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

sp_thresholdaction 을 이용해서 dump tran 을 한다

7.log 8.system table

9.tempdb 9.tempdb tempdb 줄이는 법은? tempdb full 난 경우는(Msq # 1105) 어떻게 해야 하나? tempdb 크기 산정은? tempdb 위치는? tempdb 에서 system table 에 lock 이 걸리는 경우 tempdb 가 master device 에서 더 이상 사용되게 하지 않으려면?

performance 관련하여 추천사항?

tempdb tempdb 줄이는줄이는 법은법은??여기서는 master device 의 2MB 만 남기고 줄이는 방법을 설명한다

STEP 1) 만약을 위한 조치 1) single-user mode 로 ASE 를 re-start 한다 (dataserver -m) 2) master database 을 dump 한다: 3) master database 의 복구를 위해 다음과 같은 system table 을 bcp..out 한다 master..sysusages master..sysdevices

82

Page 83: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

master..sysdatabases master..syslogins master..sysconfigures master..syscharsets STEP 2) System 정보를 변경하기 위해 ASE 의 Reconfigure:1> use master2> go

1> sp_configure "allow updates", 1 2> go

1> shutdown2> go

STEP 3) startserver 한다

STEP 4) system table 을 정정할때는 begin tran 으로 시작한다

STEP 5) sysusages table 의 tempdb 관련 row 을 본다 1> select * from sysusages 2> where dbid = db_id('tempdb') 3> go

STEP 6) 첫번째 tempdb 의 2MB 를 data and log 로 변경한다 1> update sysusages 2> set segmap = 7 where dbid = db_id('tempdb') 3> and lstart = 0 4> go

STEP 7) sysusages 에서 tempdb 에 관련된 다른 Row 을 삭제한다 1> delete sysusages where dbid = db_id('tempdb') 2> and lstart != 0 3> go

주의! restart 때 model database 을 copy 하여 tempdb 을 생성하므로, tempdb 을 model database 보다 적지 않아야 한다.

STEP 8) sysusage 에서 다음을 확인해 결과가 똑같아야 한다 1> select * from sysusages 2> where dbid = db_id('tempdb')

dbid segmap lstart size vstart --- ------ ----- ---- ------ 2 7 0 1024 2564

STEP 9) 위의 결과와 같으면, commit transaction 을 하면 된다1> commit tran2> go

위의 결과와 같지 않으면, rollback transaction 을 하면 된다1> rollback transaction2> go

STEP 10) System catalog 정보를 변경하지 못하도록 configuration 을 변경한다1> sp_configure "allow updates", 0

83

Page 84: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

2> go

STEP 11) ASE Server 에 checkpoint 을 하고 Server Re-start1> checkpoint2> go

1> shutdown2> go

tempdb full tempdb full 난난 경우는경우는(Msq # 1105) (Msq # 1105) 어떻게어떻게 해야하나해야하나??STEP 1) 필요없는 table 을 drop 한다STEP 2) STEP 1)으로 안되면, tempdb 를 확장한다STEP 3) STEP 2)으로 안되면, ASE 를 종료한다

tempdb tempdb 크기크기 산정은산정은??tempdb 의 사용은 ASE 가 distinct, not exists, group by, order by, reformatting, where 에서 or 를 사용하는 경우, aggregation 사용할 때 내부적으로 사용된다 user 가 #을 붙인 table 을 만들 때 사용된다

보통 가장 큰 query 내용을 수행을 할 수 있는 정도의 size 를 주거나 전체 data 의 10%를 주거나 또는 user 당 1~2 mb 를 주거나 한다

tempdb tempdb 위치는위치는?? tempdb 를 놓는 곳은 가장 빠른 device 위치에 놓는다 되도록 다른 job 과 경합이 적은 곳에 놓는다 여러 개 device 에 분산해 놓음으로써 여러 개의 controller 를 동시에 사용할 수 있게 한다

tempdb tempdb 에서에서 system tablesystem table 에에 locklock 이이 걸리는걸리는 경우경우많은 user 가 동시에 임시 table 을 만드는 경우에 tempdb 의 system table 에 lock contention 이 일어난다 select * into #temp_table 식으로 만드는 것 보다 create table #temp_table 을 한뒤, insert /select 하는 것이 이 점을 막을 수 있다이것은 system table, lock 은 피할 수 있으나 syslogs 에 기록하기에 느리다

tempdbtempdb 가가 master devicemaster device 에서에서 더더 이상이상 사용되게사용되게 하지하지 않으려면않으려면??STEP 1) 다른 device 로 tempdb 를 확장한다 1> alter database tempdb on ... 2> go

STEP 2) tempdb 에서 master 안에 있는 모든 segment 를 없앤다 1> use tempdb 2> go

1> sp_dropsegment "default", tempdb, master 2> go 1> sp_dropsegment "logsegment", tempdb, master 2> go 1> sp_dropsegment "system", tempdb, master 2> go

84

Page 85: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

STEP 3) 현재 master device 안에서 사용되던 영역을 모두 채운다 그 뒤부터는 master device 에서 더 이상 tempdb 용으로 쓰이는 부분이 없어진다

while ( 1 = 1 ) begin create table #x (col_a int) drop table #x end

performance performance 관련하여관련하여 추천사항추천사항?? tempdb 를 named cache 에 bind 한다 tempdb 의 syslogs table 만이라도 named cache 에 bind 한다

10.10.dbcc dbcc sybase_ts_role setting database backup 전에 무결성 check 는 어떻게 ? dbcc dbrepair dbcc checkcatalog dbcc checkdb dbcc checktable dbcc checkalloc dbcc tablealloc dbcc page dbcc memusage dbcc rebuild_log dbcc dbinfo dbcc traceon / traceoff dbcc help

sybase_ts_role settingsybase_ts_role setting dbcc 의 몇 개의 command 는 sybase_ts_role 을 요구한다sp_role 로 login-id 에 부여한다

85

Page 86: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

sp_role "grant", sybase_ts_role, sa go

set role "sybase_ts_role" ongo

확인한다select show_role()go

database backup database backup 전에전에 무결성무결성 checkcheck 는는 어떻게어떻게 ??checkcatalog, checkdb, checkalloc 을 수행한다

dbcc dbrepairdbcc dbrepairdbcc dbrepair ( database_name, dropdb)

복구할 수도 사용할 수도 없는 database 에 대해서는 drop database 를 쓸 수 없다. 즉 손상된 database 를 drop 하기 위해서는 master database 로 부터 dbcc derepair 를 사용 하여야 한다

dbcc checkcatalogdbcc checkcatalogdbcc checkcatalog (dbname)

system table 간의 일관성을 check 한다예를 들면, sysobjects 에 속한 table,view 에는 syscolumns 에 적어도 1 개의 행을 갖고 있어야 한다. syscolumns 에 있는 타입은 systypes 에 적어도 1 개의 행을 가져야 한다. syslogs table에는 마지막 checkpoint 가 유효하다는 것이 check 되어있어야 한다

1> dbcc checkcatalog2> goChecking current databaseThe following segments have been defined for database 5 (database name pubs2).virtual start addr size segments-------------------- ------ --------------------------4612 1024 0 1 2DBCC execution completed. If DBCC printed error messages, contact a user withSystem Administrator (SA) role.

dbcc checkdbdbcc checkdbdbcc checkdb (dbname [, skip_ncindex ])

db 안에 있는 모든 table 의 data,index page 의 일관성을 check 한다1> dbcc checkdb(pubs2)2> goChecking pubs2Checking sysobjectsThe total number of data pages in this table is 3.Table has 65 data rows.Checking sysindexesThe total number of data pages in this table is 6.Table has 63 data rows.

86

Page 87: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

Checking syscolumnsThe total number of data pages in this table is 10.Table has 434 data rows.Checking systypesChecking syslogsThe total number of data pages in this table is 2.*** NOTICE: Notification of log space used/free cannot be reported because thelog segment is not on its own device.Table has 23 data rows.Checking sysprotectsThe total number of data pages in this table is 1.Table has 88 data rows.Checking sysusersThe total number of data pages in this table is 1.Table has 9 data rows.Checking sysalternatesThe total number of data pages in this table is 1.Checking T1The total number of data pages in this table is 1.Table has 1 data rows.Checking app_disThe total number of data pages in this table is 1.DBCC execution completed. If DBCC printed error messages, contact a user withSystem Administrator (SA) role

87

Page 88: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

dbcc checktabledbcc checktabledbcc checktable (tablename [, skip_ncindex ])

특정 table 의 data,index page 의 일관성을 check 한다1> dbcc checktable(publishers)2> goChecking publishersThe total number of data pages in this table is 1.Table has 3 data rows.DBCC execution completed. If DBCC printed error messages, contact a user withSystem Administrator (SA) role.

dbcc checkallocdbcc checkallocdbcc checkalloc(dbname [, fix_option])

database 에서 page allocation 의 오류를 검사한다1> dbcc checkalloc(pubs2)2> goChecking pubs2Database 'pubs2' is not in single user mode - may find spurious allocationproblems due to transactions in progress.***************************************************************TABLE: sysobjects OBJID = 1INDID=1 FIRST=1 ROOT=8 SORT=0 Data level: 1. 3 Data pages allocated and 1 Extents allocated. Indid : 1. 1 Index pages allocated and 1 Extents allocated.INDID=2 FIRST=16 ROOT=16 SORT=0 Indid : 2. 1 Index pages allocated and 1 Extents allocated.TOTAL # of extents = 3***************************************************************TABLE: sales OBJID = 112003430INDID=1 FIRST=705 ROOT=697 SORT=1 Data level: 1. 1 Data pages allocated and 1 Extents allocated. Indid : 1. 1 Index pages allocated and 1 Extents allocated.TOTAL # of extents = 2***************************************************************TABLE: salesdetail OBJID = 144003544INDID=0 FIRST=529 ROOT=531 SORT=0 Data level: 0. 3 Data pages allocated and 1 Extents allocated.INDID=2 FIRST=498 ROOT=497 SORT=1 Indid : 2. 3 Index pages allocated and 1 Extents allocated.INDID=3 FIRST=714 ROOT=713 SORT=1 Indid : 3. 3 Index pages allocated and 1 Extents allocated.TOTAL # of extents = 3***************************************************************TABLE: app_dis OBJID = 1152007135INDID=0 FIRST=825 ROOT=825 SORT=0 Data level: 0. 1 Data pages allocated and 1 Extents allocated.TOTAL # of extents = 1***************************************************************Processed 62 entries in the sysindexes for dbid 5.Alloc page 0 (# of extent=32 used pages=84 ref pages=74)Alloc page 256 (# of extent=32 used pages=69 ref pages=69)Alloc page 512 (# of extent=32 used pages=130 ref pages=120)Alloc page 768 (# of extent=10 used pages=40 ref pages=37)Total (# of extent=106 used pages=323 ref pages=300) in this database

Statistical information for this run follows:

88

Page 89: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

Total # of pages read = 298Total # of pages found cache = 294Total # of physical reads = 4Total # of saved I/O = 0DBCC execution completed. If DBCC printed error messages, contact a user withSystem Administrator (SA) role.

dbcc tableallocdbcc tableallocdbcc tablealloc(objname [,report_type [,fix_option]])dbcc tablealloc(objid [,report_type [,fix_option]])

report_type : FULL, OPTIMIZED, FAST, NOREPORT (default: OPTIMIZED)fix_option : nofix, fix (default: fix)

object 의 할당정볼를 check 하고 고쳐준다1> dbcc tablealloc(publishers)2> goThe default report option of OPTIMIZED is used for this run.The default fix option of FIX is used for this run.***************************************************************TABLE: publishers OBJID = 48003202INDID=1 FIRST=633 ROOT=625 SORT=1 Data level: 1. 1 Data pages allocated and 1 Extents allocated. Indid : 1. 1 Index pages allocated and 1 Extents allocated.TOTAL # of extents = 2Alloc page 512 (# of extent=1 used pages=2 ref pages=2)Alloc page 512 (# of extent=1 used pages=2 ref pages=2)Total (# of extent=2 used pages=4 ref pages=4) in this database

Statistical information for this run follows:Total # of pages read = 4Total # of pages found cache = 4Total # of physical reads = 0Total # of saved I/O = 0DBCC execution completed. If DBCC printed error messages, contact a user withSystem Administrator (SA) role.

dbcc pagedbcc pagedbcc page (dbname, pageno [,printopt [,cache [,logical [,cachename]]]])dbcc page (dbid, pageno [,printopt [,cache [,logical [,cachename]]]])

printopt : 0,1,2,3 (default : 1 print buffer & header) cache : 0, 1 (default : 1 read page from cache if present else read page from disk)logical : 0,1 (default : 1 pageno is a logical page number)cachename: -1, null, cachename (default : null choose cache based on pageno)

database 의 해당 page 의 내용을 본다1> dbcc page(pubs2,63)2> go

Page not found in cache default data cache.Read from disk.

BUFFER:Buffer header for buffer 0x1210800 (Mass head) page=0x1211000 bdnew=0x0 bdold=0x0 bhash=0x0 bmass_next=0x0 bmass_prev=0x0 bvirtpg=4675 bdbid=5 bmass_head=0x1210800 bmass_tail=0x1210800 bcache_desc=0xea8d20

89

Page 90: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

bpool_desc=0x0 bdbtable=0x0 Mass bkeep=0 Mass bpawaited=0 Mass btripsleft=0 Mass btripsleft_orig=0 bsize=2048 (2K pool) bunref_cnt=0 bmass_stat=0x0800 (0x00000800 (MASS_NOTHASHED)) bbuf_stat=0x0 (0x00000000) Buffer bpageno=63 Mass bpageno=63 (Buffer slot #: 0) bxls_pin=0x00000000 bxls_next=0x00000000 bxls_flushseq=0 bxls_pinseq=0 bcurrxdes=0x0Latch and the wait queue:Latch (address: 0x1210830) latchmode: 0x0 (FREE_LATCH) latchnoofowners: 0 latchwaitq: 0x0 latchwaitqt: 0x0

Latch wait queue:

PAGE HEADER:Page header for page 0x1211000pageno=0 nextpg=0 prevpg=0 objid=0 timestamp=0000 00000000nextrno=0 level=0 indid=0 freeoff=0 minlen=0page status bits: 0x0 (0x0000)

dbcc memusagedbcc memusagememory 사용현황을 보여준다1> dbcc memusage2> goMemory Usage:

Meg. 2K Blks Bytes

Configured Memory: 26.0000 13312 27262976

Code size: 6.0582 3102 6352464 Kernel Structures: 4.5176 2313 4737003 Server Structures: 12.9254 6618 13553310 Cache Memory: 1.6777 859 1759232 Proc Buffers: 0.0246 13 25800 Proc Headers: 0.7930 406 831488

Buffer Cache Memory, Top 3:

Cache Buf Pool DB Id Object Id Index Id Meg.default data c 2 8 0 0.0039 2K 2 8 0 0.0039default data c 1 8 0 0.0020 2K 1 8 0 0.0020default data c 3 8 0 0.0020 2K 3 8 0 0.0020

Procedure Cache, Top 1:

Database Id: 4Object Id: 1900533804Object Name: sp_syntaxVersion: 1Uid: 1Type: stored procedure

90

Page 91: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

Number of trees: 0Size of trees: 0.000000 Mb, 0.000000 bytes, 0 pagesBytes lost for alignment 0 (Percentage of total: 0.000000)Number of plans: 1Size of plans: 0.091468 Mb, 95911.000000 bytes, 48 pagesBytes lost for alignment 2821 (Percentage of total: 2.941268)

dbcc rebuild_logdbcc rebuild_logdbcc rebuild_log (dbname, rebuild, all)dbcc rebuild_log (dbid, rebuild, all)

rebuild : 0, 1 (0: Do not create a new log.all=1 인 경우에 log 의 extent 만 지운다) (1:old log 를 모두 지우고, new log 를 만든다)all: 0, 1 (0: old log 만 지운다) (1:current log 와 old log 모두 지운다)

checkpoint 만 있는 log 를 만든다

dbcc dbinfodbcc dbinfodbcc dbinfo(dbname)

database 의 page# 24 에 있는 db 정보를 보여준다이정보는 disk reinit, replication server, recovery 와 load tran 에 사용된다1> dbcc dbinfo(user_db)2> go

DBINFO STRUCTURE:

offset 0=dbi_lastlr: (136,0)offset 8=dbi_dpbegxact: (1030,1)offset 16=dbi_oldseqnum: Jan 1 1900 12:00:00:000AM?offset 24=dbi_curseqnum: Dec 16 2000 9:24:24:546AM?offset 32=dbi_nextseqnum: Jan 1 1900 12:00:00:000AM?offset 40=dbi_deallocpgs: 10offset 44=dbi_2ndary_trunc_time_set: Jan 1 1900 12:00:00:000AM?offset 52=dbi_nextcheckpt: (empty)offset 60=dbi_dbid: 4offset 62=dbi_dbisize: 510offset 64=dbi_version: 5offset 66=dbi_status: 0x00000000(0x0000)offset 68=dbi_checkpt: (1030,13)offset 76=dbi_nextid: 3031offset 80=dbi_golden_spare_bytes[0]: 0offset 81=dbi_golden_spare_bytes[1]: 0offset 82=dbi_golden_spare_bytes[2]: 0offset 83=dbi_golden_spare_bytes[3]: 0offset 84=dbi_crdate: Dec 16 2000 9:24:23:390AM?offset 92=dbi_dbname: user_dboffset 122=dbi_status2: 0x0000(0x0000)offset 124=dbi_more_golden_spare_bytes[0]: 0offset 125=dbi_more_golden_spare_bytes[1]: 0offset 126=dbi_more_golden_spare_bytes[2]: 0offset 127=dbi_more_golden_spare_bytes[3]: 0offset 128=dbi_ldstate: 24(0x0010 (DBI_NEEDS_DUMP), 0x0008 (DBI_TRUNCATED_ONLY))offset 130=dbi_logvers: 5offset 132=dbi_rambots: 0x0000 0x00000000

91

Page 92: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

offset 140=dbi_dmplastckpt: (empty)offset 148=dbi_dmplastlr: (empty)offset 156=dbi_pretruncpg: 0offset 160=dbi_posttruncpg: 0offset 164=dbi_secondary_truncpg: 0offset 168=dbi_rep_stat: 0(0x0000)offset 170=dbi_rep_gen_id: 0offset 184=dbi_upgdvers: 25offset 188=dbi_suid: 1offset 192=dbi_dbnlen: 7offset 194=dbi_last_golden_spare_bytes[0]: 0offset 195=dbi_last_golden_spare_bytes[1]: 0offset 196=dbi_last_golden_spare_bytes[2]: 0offset 197=dbi_last_golden_spare_bytes[3]: 0offset 198=dbi_last_golden_spare_bytes[4]: 0offset 199=dbi_last_golden_spare_bytes[5]: 0offset 200=dbi_status3: 0x00000000offset 204=dbi_status4: 0x00000000offset 208=dbi_instcount: 0offset 212=dbi_spare_bytes[0]: 0offset 213=dbi_spare_bytes[1]: 0offset 214=dbi_syscolvers: 0offset 215=dbi_logspacestatus: 1offset 216=dbi_freelogpages_at_ckpt: 1019offset 220=dbi_logallocs_at_ckpt: high=0, low=9offset 228=dbi_logdeallocs: high=0, low=121offset 236=dbi_logdeallocs_at_ckpt: high=0, low=121offset 244=dbi_logallocs_at_dbtswap: high=0, low=0offset 252=dbi_unrsvd: (empty)offset 260=dbi_hilogpageno: 2047offset 264=dbi_lwm_ts: 0x0001 0x00000581offset 272=dbi_spare_ints:

dbcc {traceon / traceoff} (3604)dbcc {traceon / traceoff} (3604)dbcc traceon(3604) : dbcc 하면서 나오는 message 를 사용자 화면에 보이게 한다dbcc traceoff(3604) : dbcc 하면서 나오는 message 를 사용자 화면에 보이게 하지 않는다

dbcc traceon(3605) : dbcc 하면서 나오는 message 를 errorlog 에 넣는다dbcc traceoff(3605) : dbcc 하면서 나오는 message 를 errorlog 에 넣지 않는다

dbcc help (dbcc command)dbcc help (dbcc command)dbcc 관한 help 기능

checkcatalog Check the consistency of the system tables for a database checkdb Validates the integrity of a data and index pages for each table within a database. checktable Validates the integrity of a data and index pages for a table checkobjcache Display the cache bindings for an dbid/objid/indid. Also scan other caches for buffers in the wrong cache. chgobjname Change an object's name within a DES. chgdbname Update the dbinfo and the dbtable structure with the new name for a database. chgmaxrowsperpg Update the DES of a given object with a new max_rows_per_page value. chgobjschema Update the schema count in the DES for an object connection_hangup Closes a connection (site handler) to another server corrupt corrupt a table in the victimdb database cursorinfo Report info for a specific cursor or all cursors active for a spid dbinfo Display the dbinfo structure, page 24 of a database. This information is used by disk reinit, replication server, recovery and load tran. dbrecover Run recover on a database which has not been recovered. dbrepair Update or repair various information for a database dbtable Displays the DBTABLE structure for a database.

92

Page 93: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

delbuff Remove a buffer from the cache with the option to flush it to disk if it is dirty. delete_row Delete an index or data row from a page des Display the contents of chosen descriptor structures (DES) descount Display the bucket number and the chain size for longest chains from the hash table. desdiag engine Bring an engine online when the SQL server is booted with traceflag 1608 extentcheck Displays all extents within a database which are used by an object extentdump Displays the extent structure for a given page number. extentzap Delete extents for an object ID and indid findnotfullextents Displays all of the extent ID's for an object that have unused pages. findstranded Searches for non-syslog extents on logsegments. fix_al Detects and corrects allocation errors within a database. fix_text This command must be run against any tables which contain text columns when changing to a new multi-byte character set. flushlog Write all dirty log pages for a database force_prefetch Spefies the global I/O size prefetch value. gam Validates the integrity of gam in a database.

gettrunc Display the current status of the log transfer state for a database help Displays the syntax for the specified dbcc command indexalloc Validate and/or fix the integrity of an object's allocation for a specific indid. iosize Set a preferred size for doing I/O on an object. listoam Display the oam page(s) information for an object. locateindexpgs Display all references within an index for a specified page lock Displays the table, page, address and semaphore locks that are currently in use. log Display log records logprint Write a message to the server errorlog logtransfer Retrieve log records to be formatted by the SQL Server Log Transfer Manager and sent to Replication Server. memusage Display information on SQL server's memory usage monitor Enable/Disable/Clear SQL Server monitor counter control netmemshow Display network memory fragments netmemusage Display the buffer size, buffer status and the spid of the process for each memory fragment. object_atts Reserve, display, or modify an attribute on an OAM page object_stats Display wait times for page locks on a per database and/or object basis. page Print the contents of a page within a database pglinkage Traverse a page chain validating its integrity pktmemshow Display the read, write and overflow buffers allocated to active users printaddress Display information regarding each valild memory pool that has memory allocated to it. It also dumps a map of the addresses used by the cache datastructure. procbuf Display procedure buffer headers and proc-headers from the procedure cache. procdiag - prtipage Print the page number pointed to by each row on a specific index page pss Print the contents of a Process Status Structure rebuild_log Create a new log with a single checkpoint record rebuildextents Rebuilds the extents and the OAM pages for an object and indid reindex Validates and rebuilds indexes if necessary after the SQL server sort order has been changed. remap Convert a pre-10.0 stored procedure/view/trigger/default or rule to a system 10 format or compress a stored procedure/view/trigger/default or rule. report_al Validate the extent structures for tables and indexes resource Displays SQL server configuration information save_rebuild_log Create a new log with a single checkpoint record. The original log's extents are saved and have their extent's object ID set to '-1'. settrunc Modifies the Log Transfer Manager (LTM) information for a database show_bucket Search the buffer cache for a database page showcache Display the buffer pools for a cache. site Display an active site buffer stacktrace Print a stacktrace for any server process tablealloc Validate and/or fix the integrity of an object's allocation. textalloc Validate and/or fix the integrity of an object's allocation for text and image columns indid. traceflags Display traceflags enabled on the SQL Server traceoff Disable special server trace flags traceon Enable special server trace flags thresholds Display the threshold cache and segment array for a dbtable structure(database)

93

Page 94: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

tune Modify the current runtime values for certain SQL server configuration options on a server wide or object basis. update_tmode Modifies the current transaction mode for a stored procedure to the transaction mode specified. usedextents Display extents that are in use for a database or for a log device Display extents that are in use for a database or for a log device user_stats Display wait times for page locks on a spid basis.. xls Display the content of the PLC (Prive Log Cache) for a user or Flush all log records from the PLC onto the SYSLOGS' page chain.

94

Page 95: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

11.Table Partition 11.Table Partition 테이블 파티션 이란? 파티션 해야 할 테이블은 어떤 종류인가? 다중 디바이스를 사용하는 파티션 된 테이블을 생성하는 방법은? 파티션 테이블은 사용자 정의 세그먼트를 필요로 하는가? 파티션 테이블의 데이터 분산을 보장할 수 있는 방법은? 파티션 테이블의 데이터 분산을 점검할 수 있는 방법? clustered index 를 생성함으로써 partition skew 를 막을 수 있는가?

테이블테이블 파티션파티션 이란이란??한 테이블에 다중 페이지 체인을 생성하는 것이다

Multiple Insertion Point마지막 페이지에 Exclusive-Lock 으로 인해 다중 트랜잭션이 동시에 수행된다면 성능 저하 문제를 일으킨다. 따라서 Heap Table 을 파티션하면 다중의 페이지 체인이 생성되고 다중의 페이지 체인 수만큼 마지막 페이지가 생성되므로 Lock contention 을 줄일 수 있다

Reduced I/O Contention테이블을 파티션하면 서버가 캐쉬의 정보를 디스크에 저장할 때 I/O Contention 을 해소할 수 있다. 테이블 세그먼트가 여러 개의 물리적인 디스크를 포함한다면 서버는 파티션 생성시 각 디스크로 테이블 파티션을 분산 시킨다. 물리적인 디스크에 대한 I/O 는 병렬로 처리될 수 있다. 성능 향상을 위해서 테이블 파티션에서 사용하는 세그먼트는 다중의 물리적인 디스크를 포함하는 Fragment 로 구성되어 있어야 한다

병렬 QUERY 처리Query 수행 시 병렬적으로 한다

파티션파티션 해야해야 할할 테이블은테이블은 어떤어떤 종류인가종류인가 ?? Heap table 이나 Clustered index 를 안 갖는 테이블에 대해서 병렬 Query 를 수행 모든 트랜잭션이 저장되는 'append-only' heap테이블 History 혹은 Audit list 를 저장하는 테이블 Bcp in 을 작업을 수행하는 새로운 테이블

다중다중 디바이스를디바이스를 사용하는사용하는 파티션된파티션된 테이블을테이블을 생성하는생성하는 방법은방법은??아래의 예는 'default segment' 가 아닌 새로운 세그먼트를 생성하여 세 개의 디바이스에 테이블을 파티션하는 예이다

STEP 1)세그먼트 생성1> sp_addsegment newsegment, my_database, data_dev12> go

95

Page 96: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

STEP 2)3 개의 디바이스로 세그먼트 확장1> sp_extendsegment newsegment, my_database, data_dev22> go1> sp_extendsegment newsegment, my_database, data_dev32> go

STEP 3)세그먼트 상에 테이블 생성1> create table my_table2> (names, varchar(80) not null)3> on newsegment4> go

STEP 4)테이블 파티션 작업1> alter table my_table partition 32> go

파티션파티션 테이블은테이블은 사용자사용자 정의정의 세그먼트를세그먼트를 필요로필요로 하는가하는가??그렇지 않다. 각 테이블은 기본적으로 'default segment'라는 기본 세그먼트에 할당되고, 테이블이 파티션 되었다면 'default segment'에 할당된 디바이스들 사이에 분산 파티션 된다

파티션된파티션된 테이블의테이블의 데이터데이터 분산을분산을 보장할보장할 수수 있는있는 방법은방법은?? 자료의 균등한 분산을 하기 위한 과정STEP 1) 파티션 된 테이블의 인덱스를 삭제한다STEP 2) parallel bcp 를 이용하여 지정된 파티션으로 자료를 복사한다. 데이터 load 후에 clustered index 를 생성하려고 한다면 자료를 순서대로 복사한다STEP 3) ASE 11.5 의 'create clustered index ..with sorted_data' 명령을 이용하여 clustered index 를 생성한다STEP 4) 파티션 된 테이블에 clustered index 를 생성하여 자료를 balance 시킬 수 있으나 자료가 균등하게 분산되지 못해서 병행 처리가 정상적으로 수행되지 않는다면 i – iii 까지 작업을 수행해야 한다STEP 5) Clustered index 를 수행하기 전에 수행할 작업테이블을 파티션 한다최소한 파티션 수보다 크도록 'number of worker processes' 와 ' max parallel degree' 서버 configuration 을 설정한다Sp_dboption 을 이용하여 'select into/bulkcopy'를 true 로 설정 한 후 checkpoint 명령을 수행한다

11.5 이전 버젼의 테이블은 다시 파티션을 수행해야 정확한 통계 정보를 얻을 수 있어 parallel query processing 효과를 얻을 수 있다. 'alter table ... unpartition' 명령어 수행 후 'alter table ... partition' 명령을 수행하면 파티션을 재생성 해준다

파티션 된 테이블에 대하여 정확한 통계 정보 및 파티션이 균등하게 되어 있는지 모니터링을 수행해야 한다 1) Statistics accuracy optimizer 가 최적의 query plan 을 선택할 수 있도록 정기적으로 'update partition statistics' 명령어를 수행하거나 'update all statistics' 명령을 수행하여 파티션에 대한 제어 정보 및 인덱스에 대한 통계 정보를 정확하게 유지해야 한다 2) partition skew 각 파티션이 포함하고 있는 데이터 페이지 수가 다르다면 병행 처리 성능에 문제가 될 수 있다. Sp_help 명령을 이용하여 파티션된 테이블에 대한 Ratio(Max/Avg)를 확인하여 2 보다 작은 값을 유지해야 한다

96

Page 97: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

파티션된파티션된 테이블의테이블의 데이터데이터 분산을분산을 점검할점검할 수수 있는있는 방법방법?? sp_help 파티션 정보를 포함한 테이블의 자세한 정보를 출력한다

sp_helpartition데이터 분산에 대한 요약 정보 및 파티션에 대한 데이터 페이지 수 정보를 출력한다

sp_helpsegment세그먼트의 각 디바이스에 대한 free page 를 출력한다

clustered indexclustered index 를를 생성함으로써생성함으로써 partition skewpartition skew 를를 막을막을 수수 있는가있는가??

파티션 된 테이블에 clustered index 를 생성하는 것은 균형잡인 파티션을 생성할 수 있다. 따라서 데이터 페이지는 인덱스 생성 후 테이블 파티션 사이에 균일하게 분산된다인덱스 생성시 첫 단계는 샘플링 데이터를 추출하는 단계로 작은 양의 행들을 읽는다. balancing은 이 샘플이 얼마나 정확한 가에 달려 있다optimizer 가 query plan 을 생성하는 동안 인덱스를 정확하게 선택할 수 있도록 정기적으로 update statistics 명령을 수행해야 한다

파티션 된 테이블이 skew 된 경우는 다음과 같다테이블이 파티션 된 후에 모든 데이터 페이지가 첫 파티션에 존재많은 행이 한 파티션으로 부터 insert 나 delete 되었다 많은 행이 한 파티션에서 'not in-place' 방법으로 update 가 발생하였다많은 행이 하나 혹은 하나 이상의 파티션으로 bulk-copy 되었다insert 가 빈번하게 롤백 되었다

파티션 된 테이블을 균등하게 조정하는 방법은 다음과 같다모든 데이터를 bcp out, 테이블을 truncate 시키고 각 파티션에 동일한 양의 자료가 입력될 수 있도록 parallel bcp 를 사용한다테이블에 clustered index 를 생성한 후 sp_help 명령으로 balance 를 확인한다

97

Page 98: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

UTILITY

1.bcp 1.bcp Syntax os file 의 data 순서와 갯수가 table column 과 일치하지 않는 경우? os file 에 있는 일정길이로 column 의 값을 갖고 있으며 구분자가 없는 경우는? 여러 종류의 BCP format File 정리 특정 column 만 bcp out 할 수 있는가? Performance 를 향상하려면? (-Q) : null column 값을 허용하면서 os file 내 구분자가 없는 경우는? (-E) : Identity column 의 값을 명시적으로 지정하는 방법은? (-A) : Network packet size 를 조정하는 방법은? (-e) : bcp 를 하면서 error 나오는 받는 file 을 지정하는 방법은? (-F) (-L) : file 에서 몇번째부터 몇번째까지 bcp 할 것인지 정할 수 있는가? (-T) : text, image column 이 있는 경우에 DATA 가 잘릴 경우는? (-b) : bcp 로 넣는 transaction 단위를 정하고 싶은 경우? database 전체의 user table 를 bcp 받는 script 작성 partition table 에 parallel bcp 어떻게 하나? 주의사항

SyntaxSyntax os file 과 DB 간의 데이터 이행 시 주로 사용되는 Utility 이다 dump 이외의 backup 방법으로 사용된다 table 단위로 실행하며, table 내의 data 값만을 처리한다 (즉 table 정보는 보관되지 않음)

bcp [[database_name.]owner.][view_name | table_name [:partition_id]] {in|out} datafile[-c] [-E] [-n] [-N] [-X][-a display_charset][-A packet_size][-b batchsize][-e errfile][-f formatfile][-F firstrow][-g id_start_value][-I interfaces_file][-J client_charset][-L lastrow][-m maxerrors][-P password][-q datafile_charset][-r row_terminator][-R remote_server_principal][-S server]

98

Page 99: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

[-t field_terminator][-T text_or_image_size][-U username][-z language]

db (pubs2)에서 owner (dbo)이고 table publishers (pubs2..publishers) 을 bcp out (out) 한다이때 os file 은 (/tmp/osfile.txt)에 값을 저장하며 file 의 내용은 볼 수 있게 (-c)한다[UNIX ] bcp pubs2..publishers out /tmp/osfile.txt -c -Usa -PStarting copy...3 rows copied.Clock Time (ms.): total = 1 Avg = 0 (3000.00 rows per sec.)

os fileos file 의의 data data 순서와순서와 갯수가갯수가 table columntable column 과과 일치하지일치하지 않을않을 경우는경우는?? format file 을 이용한다

2 개의 table 이 있다publishers 의 column 은 pub_id, pub_name, city, state 이고publishers_copy 의 column 은 pub_id, state, city 이다

STEP 1) publishers 의 data 를 bcp 로 받는데, 이때 format file 을 만든다bcp pubs2..publishers out publishers.dat -Usa -Psybtech1

Enter the file storage type of field pub_id [char]:Enter prefix-length of field pub_id [0]:Enter length of field pub_id [4]:Enter field terminator [none]: #

Enter the file storage type of field pub_name [char]:Enter prefix-length of field pub_name [1]:Enter field terminator [none]: #

Enter the file storage type of field city [char]:Enter prefix-length of field city [1]:Enter field terminator [none]: #

Enter the file storage type of field state [char]:Enter prefix-length of field state [1]:Enter field terminator [none]: \n

Do you want to save this format information in a file? [Y/n] y

Host filename [bcp.fmt]:

Starting copy...

3 rows copied.Clock Time (ms.): total = 1 Avg = 0 (3000.00 rows per sec.)

만들어진 format file 인 bcp.fmt 의 내용은 다음과 같다10.041 SYBCHAR 0 4 "#" 1 pub_id2 SYBCHAR 1 40 "#" 2 pub_name3 SYBCHAR 1 20 "#" 3 city4 SYBCHAR 1 2 "\n" 4 state

table 의 내용은 publishers.dat 파일에 다음과 같이 받쳤다New Age Books#Boston#MA0877#Binnet & Hardley#

99

Page 100: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

Washington#DC1389#Algodata InfosystemsBerkeley#CA

STEP 2) publishers_copy 테이블에 publishers.dat 내용을 넣기 위해 format file 을 수정한다[syb-sun:/tmp 83 ] cat bcp2.fmt10.041 SYBCHAR 0 4 "#" 1 pub_id2 SYBCHAR 1 40 "#" pub_name3 SYBCHAR 1 20 "#" 3 city4 SYBCHAR 1 2 "\n" 2 state

STEP 3) bcp 를 수행시킨 다음, 그 결과를 본다bcp pubs2..publishers_copy in publishers.dat -f bcp2.fmt -Usa -Psybtech1

Starting copy...

3 rows copied.Clock Time (ms.): total = 1 Avg = 0 (3000.00 rows per sec.)

~[syb-sun:/tmp 82 ] isql -Usa -Psybtech11> use pubs22> go1> select * from publishers_copy2> go pub_id state city ------ ----- -------------------- 0736 MA Boston 0877 DC Washington 1389 CA Berkeley

(3 rows affected)

원래의 publishers 테이블의 내용과 비교한다1> select pub_id,state,city from publishers2> go pub_id state city ------ ----- -------------------- 0736 MA Boston 0877 DC Washington 1389 CA Berkeley

(3 rows affected)

os fileos file 에에 있는있는 일정길이로일정길이로 column column 값을값을 갖고갖고 있으며있으며 구분자가구분자가 없는없는 경우는경우는?? format file 을 이용한다 bcp format 을 정할 때1) type 은 char 을 쓴다2) prefix length 는 0 를 사용한다 (이것이 고정길이를 나타낸다)3) column length 는 os file 내 해당 column 의 값을 갖는 길이를 사용한다4) 제일 마지막의 field terminator 는 row terminator 와 같은 것으로 \n 은 줄바꿈을 의미한다

STEP 1) pubs2..TESTTAB 를 bcp 로 format 을 이용해 받아본다1> use pubs22> go1> create table TESTTAB ( col1 int, col2 int, col3 int )2> go1> select * from TESTTAB2> go

100

Page 101: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

col1 col2 col3 ----------- ----------- ----------- 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5(5 rows affected)

STEP 2) bcp 수행한다 [syb-sun:/ase/ase12/ASE-12_0/install 96 ] bcp pubs2..TESTTAB out TESTTAB.DAT \ -Usa -Psybtech1

Enter the file storage type of field col1 [int]: charEnter prefix-length of field col1 [1]: 0Enter length of field col1 [12]: 3Enter field terminator [none]:

Enter the file storage type of field col2 [int]: charEnter prefix-length of field col2 [1]: 0Enter length of field col2 [12]: 3Enter field terminator [none]:

Enter the file storage type of field col3 [int]: charEnter prefix-length of field col3 [1]: 0Enter length of field col3 [12]: 3Enter field terminator [none]: \n

Do you want to save this format information in a file? [Y/n] y

Host filename [bcp.fmt]:

Starting copy...

5 rows copied.Clock Time (ms.): total = 1 Avg = 0 (5000.00 rows per sec.)

TESTTAB.DAT 파일의 내용을 보면 다음과 같다1 1 12 2 23 3 34 4 45 5 5

TESTTAB2.DAT 파일의 내용을 보면 다음과 같다6 6 67 7 78 8 89 9 90 0 0

STEP 3) TESTTAB2.DAT 파일의 내용을 pubs DB 에 TESTTAB Table 에 넣는다 [syb-sun:/ase/ase12/ASE-12_0/install 102 ] bcp pubs2..TESTTAB in TESTTAB2.DAT \-fbcp.fmt -Usa -Psybtech1

Starting copy...

5 rows copied.Clock Time (ms.): total = 1 Avg = 0 (5000.00 rows per sec.)

STEP 4) 확인한다[syb-sun:/ase/ase12/ASE-12_0/install 103 ] isql -Usa -Psybtech11> use pubs2

101

Page 102: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

2> go1> select * from TESTTAB2> go col1 col2 col3 ----------- ----------- ----------- 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5 6 6 6 7 7 7 8 8 8 9 9 9 0 0 0

(10 rows affected)

여러여러 종류의종류의 BCP format FileBCP format File 정리정리 Table 의 Column 이 OS Data 보다 많을 때 bcp in10.0 31 SYBCHAR 0 4 "" 1 pub_id2 SYBCHAR 0 30 "" 2 pub_name3 SYBCHAR 0 20 "\n" 4 state

OS Data 가 Table Column 보다 많을 때 bcp in10.051 SYBCHAR 0 6 "" 1 pub_id2 SYBCHAR 0 80 "" 2 pub_name3 SYBCHAR 0 12 "" 3 city4 SYBCHAR 0 15 ""5 SYBCHAR 0 4 "\n" 4 state

Table Column 순서와 OS Data File 순서가 다른 경우10.04 1 SYBCHAR 0 4 "" 1 pub_id2 SYBCHAR 0 40 "" 2 pub_name3 SYBCHAR 0 20 "" 4 state4 SYBCHAR 0 2 "\n" 3 city

특정특정 columncolumn 만만 bcp outbcp out 할할 수수 있는가있는가?? 원하는 column 으로 구성된 view 를 작성한다. view 를 bcp out 하면 된다

PerformancePerformance 를를 향상하려면향상하려면?? Packet size 를 크게 조정함으로써 Perfomance 를 향상시킬 수 있다. Trigger 를 disable 시킨 뒤 한다 insert 하려는 row 가 전체의 20 % 이상이면 모든 index,trigger 를 없애고 한다10 ~ 20 % 이면 non-clustered index 를 없애고 한다

bcp slow : index, trigger 가 존재하면 bcp slow 를 이용할 수 밖에 없다 그러면 bcp 에 의해 insert 되는 row 가 모두 syslogs 에 기록되어 속도가 느리다bcp fast : index, trigger 가 없는 상태로 syslogs 에 insert 내용은 기록되지 않고, page 할당정보만 syslogs 에 기록된다

102

Page 103: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

(-Q) : null column(-Q) : null column 값을값을 허용하면서허용하면서 os file os file 내내 구분자가구분자가 없는없는 경우는경우는?? column 이 null 을 허용할 때, prefix 를 0 으로 주고 format file 을 만들 때 사용한다

table 의 column 들이 null 을 허용한다create table kkk(IGCODE1 CHAR(3) null,IGCODE2 CHAR(6) null,GLB_DTIME CHAR(9) null,DYMD1 CHAR(9) null,DYMD2 CHAR(9) null,DYMD3 CHAR(9) null,HDESC1 CHAR(31) null,HDESC2 CHAR(51) null,XDATE CHAR(9) null)

위 table 의 format file 을 만들 때, prefix 를 0 로 하면 다음 error 가 발생한다 [sybase:/home/xpert/mgt_bcp/bcp_fmt]#bcp total_db..kkk out kkk.csv -Usa -Phj1234Enter the file storage type of field IGCODE1 [char]:Enter prefix-length of field IGCODE1 [1]: 0Enter length of field IGCODE1 [3]:Enter field terminator [none]:Internal Message: - Msg 999, Level 11, State 0:[generic/ctbcp/interact.c/233] ctbcp: readFormatFileInteractive(): Both terminator and prefix cannot be null for nullable column.

(-E) : Identity column(-E) : Identity column 의의 값을값을 명시적으로명시적으로 지정하는지정하는 방법은방법은?? identity 가 선언 되어 있을 때 text 자료값 그대로 BCP IN 하고자 할 때 사용한다1) -E Option 을 사용하면 가능하다2) -g 플래그를 함께 사용할 수 없습니다3) -N 매개변수를 지정하지 않을 경우 Adaptive Server 는 ID열을 데이터 파일로 복사합니다

bcp webbank..PB_FcashCardAccident in pb_FcashCardAccident -Usa -P -c -E

(-A) : Network packet size(-A) : Network packet size 를를 조정하는조정하는 방법은방법은?? Packet Size 를 조정하는 Option 이며 sp_configure 로 'max network packet size' 확인하여 그 범위 안에서 조정가능하며 BCP Performance 를 향상시킬 수 있다

packet 을 4096 으로 잡는다bcp webbank..PB_FcashCardAccident in pb_FcashCardAccident -Usa -P -c -A4096

(-e) : bcp(-e) : bcp 를를 하면서하면서 errorerror 나오는나오는 받는받는 filefile 을을 지정하는지정하는 방법은방법은?? bcp 수행시 문제가 있는 행을 저장하는 오류 파일 의 전체 경로 이름이다 bcp 프로그램의 오류 메시지는 터미날에 나타난다 이 매개 변수를 지정하지 않으면 bcp 는 오류 파일을 작성하지 않는다

오류 file 을 /sybase/tmp/bcperr.txt 로 지정한다bcp webbank..PB_FcashCardAccident in pb_FcashCardAccident -Usa -P -c -e/sybase/tmp/bcperr.txt

(-F) (-L) : file(-F) (-L) : file 에서에서 몇번째부터몇번째부터 몇번째까지몇번째까지 bcpbcp 할할 것인지것인지 정할정할 수수 있는가있는가?? bcp 수행을 전체가 아닌 일부로 제한할 수 있다 F 은 from 의미이고, L 은 to 의미이다

103

Page 104: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

입력 파일에서 10 line 부터 끝까지를 bcp in 한다 (기본값은 제일 첫행)bcp webbank..PB_FcashCardAccident in pb_FcashCardAccident -Usa -P -c -F10

입력 파일에서 처음부터 20 line까지를 bcp in 한다 (기본값은 제일 마지막행)bcp webbank..PB_FcashCardAccident in pb_FcashCardAccident -Usa -P -c -L20

ABC 라는 Table 의 3-5 번째 row 를 bcp out 한다1> select * from ABC2> go a ----------- 1 2 3 4 5 6 7 8 9

[digital:/home/ase12 45 ] bcp pubs2_new..ABC out ABC3-5 -F3 -L5 -c -Usa -Psybase

Starting copy...

3 rows copied.Clock Time (ms.): total = 1 Avg = 0 (2000.00 rows per sec.)

[digital:/home/ase12 46 ] cat ABC3-5345

(-T) : text, image column(-T) : text, image column 이이 있는있는 경우에경우에 DATADATA 가가 잘릴잘릴 경우는경우는??image 나 text 같은 blob datatype 을 사용하는 경우 사용하는 옵션이다-T 옵션을 주지 않으면, 처리하는 default size 는 32K 이다.

만약, bcp 를 하려는 table 이 blob 를 갖는다면 다음 2 가지 방법 -T 를 결정한다

방법 1) 현재 blob column 의 길이를 datalength함수로 최대값을 알아본다1> select max(datalength(imagerow)) from imagetable2> go

방법 2) image,text 의 최대 허용 size 는 2Giga 이므로 최대값을 -T 다음에 기술한다bcp pubs2..imagetable out imagetable.file -Usa -P -c -T2147483648

(-b) : bcp(-b) : bcp 로로 넣는넣는 transactiontransaction 단위를단위를 정하고정하고 싶은싶은 경우경우??bcp in 에서만 영향이 있다기본적으로 bcp in 은 1 transaction 으로 처리한다transaction 의 크기를 조절하기 위해 -b 옵션을 사용한다

database database 전체의전체의 user tableuser table 를를 bcpbcp 받는받는 scriptscript 작성작성STEP 1) 아래의 내용으로 된 파일을 만든다use pubs2go

104

Page 105: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

select"bcp "+rtrim(db_name())+"."+rtrim(user_name(uid))+"."+rtrim(name)+ " out "+name+".out -c -Usa -Ppassword"from sysobjectswhere type="U"go

STEP 2) isql 을 통해 bcp 받는 문장을 받는다isql -Usa -P < a > a.out

partition tablepartition table 에에 parallel bcp parallel bcp 어떻게어떻게 하나하나??partition 번호를 명시하고 bcp 를 동시에 여러 개 한다

data 가 여러 파일 titles_1,titles_2,titles_3 에 있는 경우unix % bcp pubs2..titles:1 in tiles_1&unix % bcp pubs2..titles:2 in tiles_2&unix % bcp pubs2..titles:3 in tiles_3&

data 가 한 파일 titles_1 한 곳에 있는 경우unix % bcp -L 1000 pubs2..titles:1 in tiles_1&unix % bcp -F 1001 –L 2000 pubs2..titles:2 in tiles_1&unix % bcp -F 2001 –L 3000 pubs2..titles:3 in tiles_1&

주의사항주의사항 가장 중요한 것은 column,row terminator(구분자)가 실제 data 안에 있으면 안 된다 Table 에 Index 나 Trigger 가 없으면 빠른 bcp in 이 된다 이때는 syslogs 에 insert 사항을 기록하지않고, Page Allocation 정보만 Log 된다 Database Option 인 "select into/bulkcopy"가 True 로 Setting 되어야 함 Default 는 수행된다 Rule, Trigger 가 수행되지 않는다 lock 의 개수가 모자라는 상황을 예상해야 한다 sp_configure "number of lock" 의 현재 값을 확인한다 log full 에 유의하여야 한다1) log space 를 추정해서 늘려주거나 2) db option "trunc log on chkpt" 걸거나3) -b 옵션으로 transaction size 를 작게 하거나

4) dump tran db 명 with truncate-only 를 자주 해 준다

105

Page 106: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

2.defncopy 2.defncopy Syntax어떤 권한이 있어야 defncopy 사용할 수 있는가?사용 예는? table 이나 constraint 는 어떻게 ddl 을 알아낼 수 있는가?

SyntaxSyntaxdatabase 의 특정 object (views, rules, defaults, triggers, or procedures)의 definition 을 OS file 로 추출하거나 OS file 로 존재하는 내용을 database 의 object 로 생성한다

defncopy [-X] [-a display_charset] [-I interfaces_file] [-J [client_charset]] [-P password] [-R remote_server_principal] [-S [server]] [-U username] [-z language] {in filename

dbname | out filename dbname [owner.]objectname [[owner.]objectname...] }or

defncopy -v

어떤어떤 권한이권한이 있어야있어야 defncopydefncopy 사용할사용할 수수 있는가있는가?? defncopy out 시, sysobjects 와 syscomments 에 대한 select permission 을 가져야 한다 defncopy in 시, 생성하고자 하는 object 에 대한 create 권한을 가져야 한다

사용사용 예는예는??

1> create proc PROC_ABC as2> select * from sysobjects3> return4> go

예) defncopy outdefncopy 를 통해 위에서 만든 procedure 를 PROC_ABC.txt 라는 file 로 ddl 을 받는다

106

Page 107: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

[UNIX] defncopy -Usa -Psybase out PROC_ABC.txt pubs2_new dbo.PROC_ABC[digital:/home/ase12 22 ] cat PROC_ABC.txtcreate proc PROC_ABC asselect sysobjects.name, sysobjects.id, sysobjects.uid, sysobjects.type, sysobjesreturn

/* ### DEFNCOPY: END OF DEFINITION */

예) defncopy indefncopy 를 통해 procedure 를 만든다[UNIX] defncopy -Usa -Psybase in PROC_ABC.txt pubs2_new[UNIX] isql -Usa -Psybase1> use pubs2_new2> go1> sp_helptext PROC_ABC2> go # Lines of Text --------------- 2

(1 row affected)text

-----------------------------------------------------------------------

create proc PROC_ABC asselect sysobjects.name, sysobjects.id, sysobjects.uid, sysobjects.type, sysobje

rig, sysobjects.instrig, sysobjects.updtrig, sysobjects.seltrig, sysobsreturn

(2 rows affected)(return status = 0)

tabletable 이나이나 constraintconstraint 는는 어떻게어떻게 ddlddl 을을 알아낼알아낼 수수 있는가있는가??Sybase Central 을 이용한다

107

Page 108: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

3.dscp3.dscp interfaces 파일을 edit 하려면? network환경이 바뀐후, ASE 가 start 되지 않는다면? ASE 가 두개의 port 를 다 사용하게 하고 싶다면?

interfaces interfaces 파일을파일을 editedit 하려면하려면?? dscp 라는 utility 를 이용한다

networknetwork환경이환경이 바뀐후바뀐후, ASE, ASE 가가 startstart 되지되지 않는다면않는다면?? dscp 를 통해 현재 network환경으로 바꾼다

STEP 1) OS prompt 에서 dscp 을 실행한다.STEP 2) open InterfacesDriver 를 친다STEP 3) mod Server_name 을 친다STEP 4) Transport Type 을 enter 치고 넘어간다STEP 5) Transport Address 부분에 hostname ( or ip address )와 port number 를 친다STEP 6) 다시 Transport Type 이 나오면 그냥 Enter 를 친다STEP 7) quit 로 빠져 나온다

[syb-sun:/ase/ase12 1 ] dscp

>> openokFailOver to Interface Driver.Session 1 InterfacesDriver>> list

Server objects found: Tech ASE119 DCI_S SUN_ASE119 DIGITAL_ASE12A BYPASS_back ase12 ase12_back ASE119_back

Session 1 InterfacesDriver>> mod ASE119Address: Transport Type: [tli tcp] Transport Address: [syb-sun 4100] syb-sun 3000 Transport Type: []

108

Page 109: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

Modified ASE119

Session 1 InterfacesDriver>> quit[syb-sun:/ase/ase12 2 ]

help 하면, 사용할 수 있는 command 를 보여준다Session 1 InterfacesDriver>> helphelp, h, ? -- This screen.open [DSNAME] -- Open a session for the default directory service, or the DSNAM.close [SESS] -- Close the session numbered SESS, or the current one.sess -- List all the sessions.[switch] SESS -- Make session numbered SESS the current session.add SERVER_NAME -- Add a new server object to the directory service.read SERVER_NAME -- Read the content of a server object.mod SERVER_NAME -- Modify an existing server object.addattr SERVER_NAME -- Add an attribute to an existing server object.del SERVER_NAME -- Delete an existing server object.list [all] -- List all the server objects.copy NAME1 to { SESS NAME2 | SESS | NAME2 } -- Copy the object NAME1 to a new o.copyall to SESS -- Copy all the server objects in the current session to the se.delete-all -- Delete all the server objects in the current session.config -- List the current configuration.exit, quit -- Exit program.

ASEASE 가가 두개의두개의 portport 를를 다다 사용하게사용하게 하고하고 싶다면싶다면?? dscp 통해 interfaces 에 다음과 같이 2 개의 port 를 넣는다[digital:/home/ase12 35 ] cat interfacesASE12A master tcp ether digital 7100 query tcp ether digital 7100 master tcp ether digital 7101 query tcp ether digital 7101

ASE12_7100 master tcp ether digital 7100 query tcp ether digital 7100

ASE12_7101 master tcp ether digital 7101 query tcp ether digital 7101

ASE 를 start 한 뒤, errorlog 를 보면 다음과 같이 2 개의 port 를 사용하고 있다고 나온다00:00000:00002:2000/12/05 16:14:20.06 kernel network name digital, type ether,port 710000:00000:00003:2000/12/05 16:14:20.11 kernel network name digital, type ether,port 7101

실제로 unix 상에서 해당 port 를 잡고 있는지 확인 할 수 있다[digital:/home/ase12/ASE-12_0/install 23 ] netstat -a | grep 71tcp 0 0 digital.7100 *.* LISTENtcp 0 0 digital.7101 *.* LISTEN

7100 port 를 이용해서 connection 한다[digital:/home/ase12/ASE-12_0/install 24 ] isql -Usa -Psybase -SASE12_71001> exit

109

Page 110: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

7101 port 를 이용해서 connection 한다[digital:/home/ase12/ASE-12_0/install 25 ] isql -Usa -Psybase -SASE12_71011> exit

다른 ip 도 위와 같은 방법으로 2 개 이상을 사용할 수 있다

4.optdiag4.optdiag Syntax optdiag 는 언제 사용하는가? 간단한 예제 (output) 과 그 해석 Input mode 수행 주기 reorg 에 이용

SyntaxSyntaxoptdiag [ binary ] statistics

{ -i input_file | database[.owner[.[table[.column]]]][ -o output_file ] }[ -U username ] [ -P password ]

[ -I interfaces_file ] [ -S server ][ -v ] [ -h ] [ -Tflag_value ]

[ -z language ] [ -J client_charset ][ -a display_charset ]

binary : 같은 Database 의 Output 정보가 Input File 정보로 쓰일 때 효과적이다 (Numeric Precision 유지, Rounding Error 소거)-i input_file : optdiag 에 Input 으로 사용될 OS File 이름-o output_file : optdiag 부터 Output 으로 저장될 OS File 이름-T flag_value< Flag value >

1 Input file 에서 ASE Version 과 optdiag version 과 맞지 않을 때멈추지 말것2 Input mode 에서 “Next table is table_name” Messages 를 Print4 Input mode 에서 histogram 을 loading 하는 중에 Step 숫자의일관성을

Check 하지 말고 Skip 하라6 Input mode 동안에 Input file 의 line display

OptdiagOptdiag 는는 언제언제 사용하는가사용하는가?? Table, Index, Column 의 통계정보를 분석하거나 변경 할 수 있다 systabstats 와 sysstatistics 에 저장되어 관리한다 Object 에 대한 통계정보의 양과 Step 을 유연성 있게 조정할 수 있다 Optimizer 가 작업하기에 더 좋고, 더 정확한 정보를 얻을 수 있다

110

Page 111: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

간단한간단한 예제예제 (output) (output) 과과 그그 해석해석

pubtune database 의 모든 table 정보를 Display 하고, Output 를 pubtune.opt 에 저장한다optdiag statistics pubtune -Usa -P -o pubtune.opt

titles Table 에 대한 정보 Displayoptdiag statistics pubtune..titles -Usa -P -o titles.opt

titles Table 의 price Column 에 대한 binary 정보 Displayoptdiag binary statistics pubtune..titles.price -Usa -P -o price.opt

price.opt 로부터 edit 된 정보를 Loadoptdiag binary statistics pubtune..titles.price -Usa -P -i price.opt

Table Statistics sample outputTable owner: "dbo"Statistics for table: "titles" Data page count: 662 Empty data page count: 10 Data row count: 4986.0000000000000000 Forwarded row count: 18.0000000000000000 Deleted row count: 87.0000000000000000 Data page CR count: 86.0000000000000000 OAM + allocation page count: 5 First extent data pages: 3 Data row size: 238.8634175691937287 Derived statistics: Data page cluster ratio: 0.9896907216494846

Data page cluster ratio1) All-Page : table을 읽는데 필요한 I/O를 측정하기 위해 사용된다. table이 page chain 순서대로 읽혀질 때 extent내에서 page가 cluster된 정도를 나타낸다. 따라서 1.0은 완벽한 clustering 상태를 의미한다2) DOL : table을 OAM scan하는데 필요한 I/O를 측정하기 위해 사용된다extent내에서 page들이 pack된 정도를 나타낸다. 따라서 1.0은 extent내의 page가 완벽하게 packing되었음을 의미한다

Input ModeInput Mode -i input_file optdiag 는 File 을 읽어서 sysstatistics, systabstats 에 저장한다 Histogram 이 입력 수행 중에 다음과 같은 Rule 에 의해 수행된다1) Step 숫자는 반드시 순차적으로 증가해야 한다.( -T4 trace flag 을 쓴 경우 제외)2) Step 에 대한 Column 값도 반드시 순차적으로 증가해야 한다3) 각각의 Cell 에 대한 가중치(Weight)는 0.0 에서 1.0 사이의 값이어야 한다4) Column 에 대한 가중치의 합계는 1.0 에 가까워야 한다5) 첫번째 Cell 은 Null 값을 표현한다. 비록 Null 을 허용하지 않는 Column 일지라도 반드시 표현한다

수행수행 주기주기 주기적으로 optdiag 를 수행하여 table statistics 와 index statistics 의 각 label 의 값을 이 전 optdiag 수행치와 비교하여 각 테이블에 대한 optdiag 의 수행 주기를 결정한다

111

Page 112: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

reorgreorg 에에 이용이용 Data row count 값과 Forwarded row count 값을 이용하여 high percentage 를 보이면 reorg forwarded_rows 를 수행한다 Data row count 값과 Deleted row count 값을 이용하여 High percentage 를 보이면 reorg reclaim_space 를 수행한다 Data page count 값과 Empty data page count 값을 이용하여 High percentage 를 보이면 reorg reclaim_space 를 수행한다 forwarded row percentage 와 unused space percentage 가 모두 높다면 reorg compact 를 수행한다

5.reorgreorg Syntax 수행 주기 자주 사용되는 Option 대규모 reorg 작업 시 성능 향상을 위해 고려할 configuration parameters

SyntaxSyntaxData-Only locked table 에서 table 과 index 의 space utilization 을 개선시킴으로써, performance 를 향상시키는 utility

수행수행 주기주기low cluster ratio for data and index pages 때문에 Large I/O operation 작업의 performance 가 좋지 않을 때

자주자주 사용되는사용되는 OptionOption rebuild : index re-creation 이 수행된다. Reorg 명령어는 sort step 을 거치지 않기 때문에 drop/create index 보다 더 효율적이다. Sort step 을 거치지 않는 이유는 table rebuild 중에 순서대로 row 를 얻기 위하여 index 를 사용하기 때문이다. 작업 수행 중에는 exclusive table lock을 취한다 Forwarded_rows : forwarded rows 를 unforward 시킨다. index 에는 forwarded row 가 없으므로 적용되지 않는다. 8 개의 transaction 단위로 commit/rollback 하는 short duration transaction 으로 수행된다 Reclaim_Space : unused space 를 다시 사용할 수 있도록 반환하는 작업을 수행한다. Short duration transaction 으로 수행된다 Compact : reclaim_space 와 forwarded_rows 를 동시에 수행한다. Short duration transaction으로 수행된다

대규모대규모 reorg reorg 작업작업 시시 성능성능 향상을향상을 위해위해 고려할고려할 configuration parametersconfiguration parameters OLTP 업무가 많지 않은 야간에 다음의 configuration parameter 를 수정한 후 reorg 작업을 수행한다 적용할 configuration parameters

Configuration parameter Default Value Reorg 적용 값

112

Page 113: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

Number of pre-allocated extents 2 31

Runnable process search count 2000 2000

Procedure cache percent 2 4

Total memory 가능한 한 많이

6.isql6.isql input/output file 을 지정할 수 있는가? OS 의 file 을 읽어 들일 수 있는가? 1> 이 나오게 하려면? OS 의 명령문을 수행하려면? 수행시간을 보여줄 수 있는가 ? SQL 문장 사용 뒤에 go 대신 다른 문자를 사용할 수 있는가? network packet size 를 늘리는 법은? Column 이름을 몇 row 마다 display 할 수 있게 하는 방법? 결과에서 컬럼 사이를 |로 구분할 수 있나? 결과를 좀더 넓게 볼 수 있는가? 결과에서 n rows affected 와 ----을 없앨 수 있는가?

input / outputinput / output 을을 지정할지정할 수수 있는가있는가??

방법 1) < , >을 사용한다isql -Usa -Psybase < /tmp/a.sql > /tmp/a.res

방법 2) -i , -o 를 사용한다isql -Usa -Psybase -i /tmp/a.sql -o /tmp/a.res

OSOS 의의 filefile 을을 읽어읽어 들일들일 수수 있는가있는가?? :r 을 사용한다[digital:/home/ase12 26 ] isql -Usa -Psybase1> :r /tmp/a.sql

1> 1> 이이 나오게나오게 하려면하려면?? reset 을 사용한다1> use pubs2_new2> go3> select * from publishers4> go5> exit6> reset

113

Page 114: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

OSOS 의의 명령문을명령문을 수행하려면수행하려면?? !!를 사용한다1> !!ls /tmp[sh:ls /tmp]0 a.res ctisql_aadEoa sp_helpdb000 a.result ctisql_aaedta sp_who1 a.sql ctisql_aafrBa sqlda.h

수행시간을수행시간을 보여줄보여줄 수수 있는가있는가 ?? -p 를 사용한다

isql -Usa -Password -p1> select * from publishers2> go pub_id pub_name city state ------ ---------------------------------------- -------------------- ----- 0736 New Age Books Boston MA 0877 Binnet & Hardley Washington DC 1389 Algodata Infosystems Berkeley CA

(3 rows affected)Execution Time (ms.): 0 Clock Time (ms.): 0

SQLSQL 문장문장 사용뒤에사용뒤에 go go 대신대신 다른다른 문자를문자를 사용할사용할 수수 있는가있는가?? -c 를 사용한다isql -c.A 1> select

name from sysusers2> .name-----------sandykimleslie(3 rows affected)

network packet sizenetwork packet size 를를 늘리는늘리는 법은법은?? -A 을 사용한다isql -Usa -Psybase -A4096

Column Column 이름을이름을 몇몇 row row 마다마다 displaydisplay 할할 수수 있게있게 하는하는 방법방법?? -h 를 사용한다

3row씩 보여주고 column header 를 찍는다 [digital:/home/ase12 38 ] isql -Usa -Psybase -h31> use pubs2_new2> go1> select * from authors2> go au_id au_lname au_fname phone address city state country postalcode ----------- ---------------------------------------- -------------------- ------------ ----------------------------------------

114

Page 115: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

-------------------- ----- ------------ ---------- 172-32-1176 White Johnson 408 496-7223 10932 Bigge Rd. Menlo Park CA USA 94025 213-46-8915 Green Marjorie 415 986-7020 309 63rd St. #411 Oakland CA USA 94618 238-95-7766 Carson Cheryl 415 548-7723 589 Darwin Ln. Berkeley CA USA 94705 au_id au_lname au_fname phone address city state country postalcode ----------- ---------------------------------------- -------------------------------- ---------------------------------------- -------------------- ----- ------------ ---------- 267-41-2394 O'Leary Michael 408 286-2428 22 Cleveland Av. #14 San Jose CA USA 95128 274-80-9391 Straight Dick 415 834-2919 5420 College Av. Oakland CA USA 94609 341-22-1782 Smith Meander 913 843-0462 10 Mississippi Dr. Lawrence KS USA 66044 au_id au_lname au_fname phone address city state country postalcode ----------- ---------------------------------------- -------------------- ------------ ---------------------------------------- -------------------- ----- ------------ ---------- 409-56-7008 Bennet Abraham 415 658-9932 6223 Bateman St. Berkeley CA USA 94705 427-17-2319 Dull Ann 415 836-7128 3410 Blonde St.

결과에서결과에서 컬럼사이를컬럼사이를 | | 로로 구분할구분할 수수 있나있나?? -s 로 column separator 사용한다

[digital:/home/ase12 40 ] isql -Usa -Psybase -s'|'1> select * from sysusages2> go dbid |segmap |lstart |size |vstart |pad |unreservedpgs| ------|-----------|-----------|-----------|-----------|------|-------------|| 1| 7| 0| 3072| 4| NULL| -5|| 1| 7| 3072| 2048| 6148| NULL| 1034|| 2| 0| 0| 1024| 4100| NULL| 391|| 2| 7| 1024| 5120| 201326592| NULL| 5092|| 2| 7| 6144| 1024| 50331648| NULL| 1024|| 3| 7| 0| 1024| 3076| NULL| 383|| 4| 3| 0| 51200| 117440512| NULL| 50560|| 4| 3| 51200| 20480| 117491712| NULL| 20480|| 4| 3| 71680| 4096| 117512192| NULL| 4096|| 4| 4| 75776| 10240| 134217728| NULL| 10224|

결과를결과를 좀더좀더 폭넓게폭넓게 볼볼 수수 있는가있는가?? -w 로 column width 를 조정한다

115

Page 116: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

예) -w100 : width 를 100 으로 한다

결과에서결과에서 n rows affected n rows affected 와와 --------을을 없앨없앨 수수 있는가있는가??다음과 같이 해 본다[digital:/home/ase12 82 ] isql -Usa -Psybase -n | \sed -e '/affected/d' \-e '/---/d' > resultfileselect * from pubs2_new..publishersgoexit[digital:/home/ase12 83 ] cat resultfile pub_id pub_name city state 0736 New Age Books Boston MA 0877 Binnet & Hardley Washington DC 1389 Algodata Infosystems Berkeley CA

116

Page 117: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

7.buildmaster7.buildmaster Syntax 언제 사용하는가? buildmaster 사용하는 방법은?

SyntaxSyntaxmaster device 를 만들고 master, model, tempdb 를 create 한다

buildmaster [-d disk] [-c cno] [-s size] [-m][-r][-q][-x]-d : master device 의 physical 이름-c : controll number. 보통은 0 이다 -s : master device 의 size 로 단위는 page 이다 ( 1 page = 2 K ) -m: master database 만 새롭게 만들 때 사용한다-r : master device mirror 된 것으로 시작한다-q : master device 에서 사용 안된 부분의 initialize 작업을 안 한다-x : model database 만 create 한다

언제언제 사용하는가사용하는가?? master device 에 이상이 생길 때 사용한다 master db 에 이상이 생겼을 때 사용한다 model db 만 다시 만들고 싶을 때 사용한다

buildmasterbuildmaster 사용하는사용하는 방법은방법은??STEP 1) Sybase ShutdownSTEP 2) 기존의 master.dat 를 다른 이름으로 mv 합니다STEP 3) buildmaster를 사용한다[digital:/home/ase12/ASE-12_0/devices 59 ] buildmaster

master disk name? /tmp/master - pyhsname 을 넣는다

master disk controller number? 0

master disk size? 15360 master device 의 size 를 page 단위로 넣는다

configuration only? (y or n) n configuratioin 만 만들건지 아닌지 선택한다

databases only? (y or n) n

skip clearing unused pages? (y or n) yMaster device: /tmp/masterwriting configuration areawriting the MASTER databasewriting the MODEL databasewriting the SYBSYSTEMDB databasewriting pages for remaining 17.99 MB, (9212 pages)17.99MB

117

Page 118: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

Buildmaster complete[digital:/home/ase12/ASE-12_0/devices 60 ] ls -al /tmp/master-rw-r--r-- 1 ase12 system 31457280 Dec 18 18:26 /tmp/master

sybsystemprocs DB 를 만들고 싶으면, database 를 만들고 insallmaster script 를 수행한다

SQL 1.Trigger 1.Trigger

Syntax Trigger 는 언제 실행되는가? 잠시동안 Trigger 를 중지할 수 있는가? 한 column 의 변화만을 대상으로 하는 trigger 도 가능한가? foreign key constraint 가 걸린 경우, trigger 통한 cascade delete? Trigger(statement level) 를 row level 로 바꾸려면? Trigger 의 내용을 보는 방법은? Trigger 가 참조하는 Object 를 찾는 방법은? 주의사항

SyntaxSyntax 트리거는 테이블에 직접 바인드 된 객체이다 테이블에 데이터 변경(insert,update,delete)을 시도할 때 자동적으로 실행된다

create trigger [owner.]trigger_name on [owner.]table_name for {insert, update, delete} as SQL_statementsOr, using the if update clause:create trigger [owner.]trigger_name on [owner.]table_name for {insert, update} as [if update (column_name) [{and | or} update (column_name)]...] SQL_statements [if update (column_name) [{and | or} update (column_name)]... SQL_statements]...

TriggerTrigger 는는 언제언제 실행되는가실행되는가?? trigger 를 기동시킨 sql 문장과 1 transaction 이다

순서를 정한다면, 기동시킨 sql 문장이 실행되고, 실행결과로 inserted 또는 deleted 라는 특별한 view 생성되고나서 수행된다고 봐도 좋다

잠시동안잠시동안 TriggerTrigger 를를 중지할중지할 수수 있는가있는가?? ASE 12.0 이후에서는 alter table 명령문에서 trigger 를 enable/disable 시킬 수 있다

1> alter table titles disable trigger deltitle2> goDisabling trigger 'deltitle'.

118

Page 119: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

1> alter table titles enable trigger deltitle2> goEnabling trigger 'deltitle'

119

Page 120: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

한한 columncolumn 의의 변화만을변화만을 대상으로대상으로 하는하는 triggertrigger 도도 가능한가가능한가?? if update(column 명)을 사용하면 가능하다여기서 변화라는 것은 값의 변화를 의미하는 것이 아니라 해당 column 의 update 수행여부를 말하는 것입니다. 만약 해당 column 의 값의 변화를 check 하고 싶다면 deleted,inserted table 의 해당 column 을 비교해서 이용해야 합니다

1>create trigger TEST_TAB_trg on TEST_TAB for insert,update,delete2>as3> if update(COL1)4> begin5> select "Updated !!"6> end7>return8>go1> insert into TEST_TAB values (1)2> go

---------- Updated !!

(1 row affected)(1 row affected)1> update TEST_TAB set COL1 = 12> go

---------- Updated !!

(1 row affected)(1 row affected)

delete 에서는 기동 되지 않는다1> delete TEST_TAB2> go(1 row affected)

foreign key constraintforeign key constraint 가가 걸린걸린 경우경우, trigger, trigger 통한통한 cascade deletecascade delete 는는?? error 가 생긴다. constraint 도 trigger 로 바꿔 구현해야 한다

parent_tab 의 primary key 를 child_tab 에서 foreign key 로 constraint 를 선언한 경우에 parent tab 의 cascade delete 를 수행하면 error 가 발생한다

이럴 경우는 parent_tab 에 delete trigger 에 cascade trigger 를 만들고, child_tab 에 insert/update trigger 를 만들어 foreign key constraint 를 대신해야 한다

parent_tab 의 primary key 는 p_col1, p_col2 이다child_tab 의 c_col1,c_col2 는 parent_tab 의 p_col1, p_col2 에 대응한다create table parent_tab (p_col1 int,p_col2 int)create table chlid_tab (c_col1 int,c_col2 int,c_col3 int)

child_tab 의 insert / update trigger 에서 parent_tab 에 없는 내용이면 i/u 못하게 한다create trigger child_tab_iu on child_tab for insert,update as declare @i_count int,@d_count int

if not exists ( select 1 from parent_tab p,inserted i where p.p_col1 = i.c_col1 and p.p_col2 = i.c_col2 )

120

Page 121: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

begin print "not in parent table"

rollback tran endreturn

parent_tab 의 delete trigger 에는 cascade delete 기능을 넣는다create trigger parent_tab_d on parent_tab for delete as

delete child_tab from child_tab, deleted dwhere c_col1 = d.p_col1and c_col2 = d.p_col2

return

child_tab insert 는 항상 parent_tab 에 있어야 한다1> select * from child_tab2> go c_col1 c_col2 c_col3 ----------- ----------- ----------- 1 1 1 2 2 2

(2 rows affected)

1> select * from parent_tab2> go p_col1 p_col2 ----------- ----------- 1 1 1 1 3 3 4 4

(4 rows affected)

parent_tab 에 7 은 없다. insert 안된다1> insert into child_tab values (7,7,7)2> gonot in parent table

parent_tab 에 있는 delete 하면 child_tab 의 내용을 삭제하는 cascade delete 를 점검한다1> delete parent_tab where p_col1 = 12> go(1 rows affected)

1> select * from parent_tab2> go p_col1 p_col2 ----------- ----------- 2 2 3 3 4 4

1> select * from child_tab2> go c_col1 c_col2 c_col3 ----------- ----------- ----------- 2 2 2

(1 row affected)

121

Page 122: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

Trigger(statement level) Trigger(statement level) 를를 row levelrow level 로로 바꾸려면바꾸려면?? cursor 를 이용한다1> create trigger del_TEST_TAB2> on TEST_TAB for delete 3> as4>5> declare @a int,@b int,@c int6>7> declare XX cursor for8> select * from deleted9>10> open XX11>12> fetch XX into @a,@b,@c13>14> while @@sqlstatus = 015> begin16> insert D_TEST_TAB values (@a,@b,@c)17> fetch XX into @a,@b,@c18> end19>20> close XX21> deallocate cursor XX22>23> return24> go

TriggerTrigger 의의 내용을내용을 보는보는 방법은방법은?? sp_helptext 로 확인할 수 있다1> sp_helptext deltitle2> go # Lines of Text --------------- 1

(1 row affected)

text

-----------------------------------------------------------------------

create trigger deltitleon titlesfor deleteasif (select count(*) from deleted, salesdetailwhere salesdetail.title_id = deleted.title_id) >0begin rollback transaction print "You can't delete a title with sales."end

TriggerTrigger 가가 참조하는참조하는 ObjectObject 를를 찾는찾는 방법은방법은 sp_depends 로 확인할 수 있다 (view,trigger,procedure 도 마찬가지이다)

1> sp_depends deltitle2> go

122

Page 123: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

Things the object references in the current database. object type updated selected ---------------------------------------- ---------------- ---------- ---------- dbo.salesdetail user table no nodbo.titles user table no no

주의사항주의사항 ASE 의 version up 시에 drop 했다가 다시 create 되어야 한다 BCP 시 INSERT TRIGGER 가 기동되지 않는다 TRUNCATE 시 DELETE TRIGGER 가 기동되지 않는다 TRIGGER 는 DEFAULT 로는 RECURSIVE 가 아니다 set self_recursive on 하면, RECURSIVE 가 된다 TRIGGER 가 작동시, PERFORMANCE 가 늦을 수 있다

123

Page 124: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

2.stored Procedures2.stored Procedures공유되는 Program 을 db 안에 넣을 수 있는가?Stored Procedure 생성 script 예.Stored Procedures 의 좋은점이 무엇인가?Errors Handlingsp 실행시 transaction mode 와 관련이 있는가? (Msg 7712)어느 db 에서 누구나 사용할 수 있는 sp 를 작성할 수 있는가?stored procedure 내용을 숨길 수 있는가?upgrade 시 stored procedure 를 drop 하고 다시 생성해야 합니까?sp_recompile 은 언제 사용합니까?stored procedure 수정은 어떻게 합니까?

공유되는공유되는 ProgramProgram 을을 dbdb 안에안에 넣을넣을 수수 있는가있는가?? stored procedure 를 통해서 할 수 있다

T-SQL 과 control-of-flow language 의 집합이라 말할 수 있다 그래서 programing 이 가능하다

User Defined Stored Procedure 와 System Stored Procedure 로 나눌수 있다

1) User defined Stored Procedure사용자에 의해 만들어진 Stored Procedure 로 Performance 를 향상 하거나 공통으로 사용하는 Function 들을 Server 에 둔다

2) System Stored ProceduresASE 에서 제공하는 Procedure 로 ‘sp_’로 시작하는 Stored Procedure 입니다

Stored Procedures 는 아래의 기능을 수행할 수 있다1) Parameter 를 갖는다2) 다른 Procedure 를 호출할 수 있다3) 호출한 Procedure 나 Batch 에 Return value혹은 Status 를 돌려준다

Stored Procedure Stored Procedure 생성생성 script script 예예..

/* template.sql *//* 수행할 database 를 명시한다 */use pubs2go/* 만약 stores procedure 이미 존재한다면, drop 단계 */if exists(select 1 from sysobjects where type = “P” and name = “stored_proc_name”)begin

drop proc stored_proc_nameendgo

/* stored procdure create 단계 */create proc stored_proc_name ( @para1 char(4) = null, @para2 char(10) = null, @para3 varchar(20) = null output

124

Page 125: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

)returngo/* stored procdure permission assign 단계 */grant execute on stored_proc_name to publicgo

Stored Procedures Stored Procedures 의의 좋은점이좋은점이 무엇인가무엇인가?? Network Traffic 의 최소화Client 는 multiple SQL statement 를 Server 에 보내는 것이 아니라 Stored Procedure 의 이름만 Send 하고, Server 또한 Application logic 의 최소 Result set 을 Client 에 Send 하게 되므로 Network 의 부하를 줄일 수 있다

Data 와 Rule 등에 대한 일관성 보장Server 에 존재하는 하나의 Application logic 을 모든 사용자가 사용하므로 Data 와 Rules 에 대한 일관성 보장이 된다

Rules 에 대한 유지관리가 쉽다여러 Client 에 Application logic 나 Rules 이 존재하는 것이 아니라 Central server 에만 존재하므로 이런 것에 대한 유지관리가 쉽다

반복적으로 사용하기 위한 최적화ASE 는 Stored Procedure 의 재사용을 위하여 Query plan 을 저장한다아래 단계처럼 일반 sql 문장이 ASE 에 들어 온 경우, syntax검사,권한 check,tree 생성하는데 반해, stored procedure 는 이미 tree 생성단계까지 해 논 상태로 query plan 을 생성한다

1) stored procedure creation 단계STEP 1) Syntax 검사STEP 2) Reference objects 에 code resolvesSTEP 3) Query tree 생성STEP 4) Sysprocedures 에 query tree 저장STEP 5) Sysobjects, syscomments system table 에 저장

2) stored Procedure 의 처음실행 단계STEP 1) Permissions 검사STEP 2) Query plan 생성STEP 3) Procedure cache 에 query plan 저장

3) stored Procedure 의 실행 STEP 1) Procedure Cache 에서 Query Plan 의 적당한 Copy 본을 찾는다STEP 2) 만약 적당한 Copy 본이 없는 경우, Proc Cache 에 Query Plan 을 새로이 생성

4) stored Procedure 를 Recompiling 할 때STEP 1) sysprocedures 로 부터 Query Tree 를 읽는다STEP 2) Permission 을 다시 체크STEP 3) Procedure Cache 에 옵티마이즈된 Query Plan 을 새로이 생성

125

Page 126: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

Errors HandlingErrors Handling return code (system 제공)

values meaning0 procedure executed without error-1 Missing object-2 Datatype error-3 Process was chosen as deadlock victim-4 Permission error-5 Syntax error-6 Miscellaneous user error-7 Resource error,such as out of space-8 Non-fatal internal problem-9 System limit was reached -10 Fatal internal inconsistency-11 Fatal internal inconsistency-12 Table or index is corrupt-13 Database is corrupt-14 Hardware error

return code (User-generated return codes)

Procedures 에서 특정 Step 의 Return 값으로 사용한다return [int_expression]

@@error : 일반적인 error 로 모든 sql 문장이후에 즉시 @@error 를 Check 해야 한다

@@transtate : User session 에서 현재 Transactions 의 State 을 나타낸다

value Meaning0 transaction 이 진행 중1 transaction 이 정상수행 됨2 이전 statement aborted,그러나 transaction 에는 영향 없음

raiserror and sp_addmessage 사용자가 Code & messages 를 직접 Define 해서 사용할 수 있다.

예) code 909090 에 내용은 'error occurs!!'을 message 로 정의한다1> sp_addmessage 909090,'error occurs!!'2> goerror occurs!!The message has been inserted.(return status = 0)

126

Page 127: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

필요시 909090 error 를 일으킨다1> raiserror 9090902> goMsg 909090, Level 16, State 1:Line 1:error occurs!!

spsp 실행시실행시 transaction modetransaction mode 와와 관련이관련이 있는가있는가? (Msg 7712)? (Msg 7712) stored procedure 작성한 transaction mode 와 실행할 때 transaction mode 가 일치해야 한다 변경하고자 할 때는 sp_procxmode 를 사용하면 된다

chained mode 에서 stored procedure TEST_PROC 을 만든다1> set chained on2> go1> create proc TEST_PROC as2> select "TEST_PROC!!"3> return4> go

unchained mode 에서 실행하면, 7712 error 가 발생한다1> set chained off2> go1> exec TEST_PROC2> goMsg 7712, Level 16, State 2:Server 'ASE12A', Line 1:Stored procedure 'TEST_PROC' may be run only in chained transaction mode. The'SET CHAINED ON' command will cause the current session to use chainedtransaction mode.

sp_procxmode 로 stored procedure 의 수행 mode 를 정한다1> sp_procxmode TEST_PROC,anymode2> go(return status = 0)1> sp_procxmode TEST_PROC,chained2> go(return status = 0)1> sp_procxmode TEST_PROC,unchained2> go(return status = 0)

수행 mode 를 맞추면, 잘 수행된다1> exec TEST_PROC2> go

----------- TEST_PROC!!

(1 row affected)(return status = 0)

어느어느 dbdb 에서에서 누구나누구나 사용할사용할 수수 있는있는 spsp 를를 작성할작성할 수수 있는가있는가??STEP 1) sybsystemprocs db 에서 sp_로 시작하는 stored procedure 명을 사용해 작성한다1> use sybsystemprocs2> go1> create proc sp_everyone as2> select "hi, everyone!!"3> go

127

Page 128: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

STEP 2) 누구나 사용할 수 있는 실행권한을 준다1> grant exec on sp_everyone to public2> go

system stored procedure 와 같이 어느 database 에서든 수행할 수 있다1> use master2> go1> sp_everyone2> go

-------------- hi, everyone!!

(1 row affected)(return status = 0)1> use tempdb2> go1> sp_everyone2> go

-------------- hi, everyone!!

stored procedure stored procedure 내용을내용을 숨길숨길 수수 있는가있는가?? sp_helphide 사용해서 할 수 있습니다

1> create proc ADD_proc ( @para1 int, @para2 int, @para3 int out)2> as3> select @para3 = @para1 + @para24> return5> go1> sp_helptext ADD_proc2> go # Lines of Text --------------- 1

(1 row affected)

text

-----------------------------------------------------------------------

create proc ADD_proc ( @para1 int, @para2 int, @para3 int out)as select @para3 = @para1 + @para2return

(1 row affected)

1> sp_hidetext ADD_proc2> go(return status = 0)1> sp_helptext ADD_proc2> goMsg 18406, Level 16, State 1:Server 'ase12', Procedure 'sp_helptext', Line 152:Source text for compiled object ADD_proc (id = 1616008788) is hidden.(return status = 1)

128

Page 129: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

upgradeupgrade 시시 stored procedurestored procedure 를를 dropdrop 하고하고 다시다시 생성해야생성해야 합니까합니까?? stored procedure 의 defncopy 또는 advantage 를 이용해서 받으시고, 재생성 해야 한다 trigger 는 stored procedure 의 일종이므로 마찬가지로 drop 후 재생성 해야 한다

sp_recompilesp_recompile 은은 언제언제 사용합니까사용합니까?? 기존에 올라와 있는 plan 이 부적합한 경우에 sp_recompile 을 한다즉, stored procedure 의 수행속도가 느린 경우에 시도한다

stored procedurestored procedure 수정은수정은 어떻게어떻게 합니까합니까??

drop proc 한 뒤, create proc 해야 한다

3.identity 4.chained Vs. unchained Mode

129

Page 130: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

4.Chained mode4.Chained mode 와와 Unchained mode Unchained mode chained / unchained setting 하는 방법? mode 확인하는 방법? client마다 기본 mode 가 다른 경우가 있다? chained / unchained 의 주요 차이? chained / unchained 의 주요 차이 예

chained / unchained settingchained / unchained setting 하는하는 방법방법?? set 명령어로 한다

Chained mode setting set chained on

Unchained mode settingset chained off

modemode 확인하는확인하는 방법방법?? select @@tranchained 로 한다chained mode 는 1 , unchained mode 는 0 이다

1> select @@tranchained2> go ----------- 0

clientclient마다마다 기본기본 modemode 가가 다른다른 경우가경우가 있다있다?? 있다isql 은 unchained mode 이고, embedded/C 는 chained mode 이다그밖의 client 개발에 사용되는 tool 도 기본 mode 를 확인한뒤 program 해야 한다

chained / unchained chained / unchained 의의 주요주요 차이차이?? Unchained Mode1) Transaction 의 끝에 자동 commit 이 붙으면서 되돌릴 수 없게 된다2) Transaction 의 수행여부를 (commit/rollback)을 미루고 싶다면, begin tran 으로 시작하고, 끝에 commit 또는 rollback 을 꼭 명시해야 한다3) 서버는 @@trancount 가 0 이 되면 Transaction 이 완료 되었다고 생각한다

Chained mode1) 묵시적으로 Begin 을 실행한다2) 반드시 commit tran 또는 rollback tran 을 표시해야 한다3) Select into 를 사용할 수 없다4) @@Trancount 가 0 이 될 수 없다

chained / unchained chained / unchained 의의 주요주요 차이차이 예예 chained mode Example1> insert into publishers values ('9999', null, null, null)2> begin transaction /* ---------- 무시된다 ---------- */3> delete from publishers where pub_id = '9999'

130

Page 131: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

4> rollback tran5> go(1 row affected)(1 row affected)1> select * from publishers where pub_id = '9999'2> go pub_id pub_name city state ------ ---------------------------------------- -------------------- -----

(0 rows affected)

unchained mode Example1> set chained off2> go1> select @@tranchained2> go

----------- 0

(1 row affected)1> insert into publishers values ('9999', null, null, null) /* --- commit 된다 --- */2> begin transaction3> delete from publishers where pub_id = '9999'4> rollback tran5> go(1 row affected)(1 row affected)1> select * from publishers where pub_id = '9999'2> go pub_id pub_name city state ------ ---------------------------------------- -------------------- ----- 9999 NULL NULL NULL

(1 row affected

131

Page 132: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

운영자매뉴얼 Veritas Cluster Server V 1.0

5.datetime5.datetime 날짜,시간을 다루는 datatype? datetime 속성의 날짜를 YYYY.MM.DD 로 보려면? 현재 system 의 시간을 보려면? 두 날짜가 몇일간인지를 알려면? "2000년 7월 25 일 오후 2 시 30 분" 이후를 where 에서 지정하려면? 날짜 넣는 방법은? 시간 넣는 방법은?

날짜날짜,,시간을시간을 다루는다루는 datatypedatatype 은은?? smalldatetime, datetime 이다

smalldatetime 인 경우 초는 나오지 않는다

a column 은 smalldatetime 으로 지정, b column 은 datetime 으로 지정한 경우입니다1> sp_help TESTdatetime2> goColumn_name Type Length Prec Scale Nulls Default_name Rule_name Identity --------------- --------------- ------ ---- ----- ----- --------------- --------------- -------- a smalldatetime 4 NULL NULL 0 NULL NULL 0 b datetime 8 NULL NULL 0 NULL NULL 0

SQL 문장을 수행한 결과를 보면 초가 0 로 나옵니다1>insert into TESTdatetime values (getdate(),getdate())2>go1> select convert(char(30),a,109),convert(char(30),b,109) from TESTdatetime2> go

------------------------------ ------------------------------ Jun 16 2000 2:15:00:000PM Jun 16 2000 2:15:10:986PM

datetime datetime 속성의속성의 날짜를날짜를 YYYY.MM.DDYYYY.MM.DD 로로 보려면보려면 ?? datetime values 의 convert 시 style 을 지정하여야 한다1> select convert(char(10),getdate(),102)2> go-----------2000.10.24

다른 style 로 보려면 다음을 참조한다

without century (yy) with century (yyyy)- 0 or 100 mon dd yyyy

hh:mm AM (or PM)1 101 mm/dd/yyyy2 102 yyyy.mm.dd3 103 dd/mm/yyyy

교보자동차보험 IT 팀 작성일 2002/01/25

Page 133: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

운영자매뉴얼 Veritas Cluster Server V 1.0

4 104 dd.mm/yyyy5 105 dd-mm-yyyy6 106 dd mon yy7 107 mon dd yy8 108 hh:mm:ss

9 or 109 mon dd yyyyhh:mm:sss AM(PM)

10 110 mm-dd-yy11 111 yy/mm/dd12 112 yymmdd

현재현재 SYSTEMSYSTEM 시간을시간을 알려면알려면?? getdate() 를 사용한다1> select getdate()2> go

-------------------------- Dec 14 2000 5:50PM

두두 날짜가날짜가 몇일간인지를몇일간인지를 알려면알려면?? datediff() 를 사용하면 된다1> select date,getdate() 'today',2> datediff(dd,date,getdate()) 'diff between'3> from sales4> godate today diff between -------------------------- -------------------------- ------------ Oct 31 1985 12:00AM Dec 8 2000 5:19PM 5517 Nov 6 1985 12:00AM Dec 8 2000 5:19PM 5511 Dec 1 1990 12:00AM Dec 8 2000 5:19PM 3660 Dec 12 1986 12:00AM Dec 8 2000 5:19PM 5110 Mar 15 1987 12:00AM Dec 8 2000 5:19PM 5017 Jul 18 1987 12:00AM Dec 8 2000 5:19PM 4892 Mar 21 1991 12:00AM Dec 8 2000 5:19PM 3550 Jul 27 1988 12:00AM Dec 8 2000 5:19PM 4517

"2000"2000년년 77월월 2525 일일 오후오후 55 시시 3535 분분" " 이후를이후를 WhereWhere 에서에서 지정하려면지정하려면??

1> select * from ZZZB2> go a b ----------- -------------------------- 1 Jul 25 2000 5:33PM 12 Jul 25 2000 5:43PM

1> select b,convert(char(8),b,2)+":"+ convert(char(8),b,8) 2> from ZZZB3>where convert(char(8),b,2)+":"+convert(char(8),b,8)>= '00.07.25:17:35:00'4> go b -------------------------- ----------------- Jul 25 2000 5:43PM 00.07.25:17:43:16

교보자동차보험 IT 팀 작성일 2002/01/25

Page 134: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

운영자매뉴얼 Veritas Cluster Server V 1.0

날짜날짜 넣는넣는 방법은방법은?? col1 은 insert 문장에서 value 로 지정한 string 이다1> select * from TIME_TAB2> go col1 col2 ------------------------------ -------------------------- Apr 15 1997 Apr 15 1997 12:00AM 1997 apr 15 Apr 15 1997 12:00AM Apr 15 1997 Apr 15 1997 12:00AM Apr 15,1997 Apr 15 1997 12:00AM Apr 1997 15 Apr 15 1997 12:00AM 15 Apr 1997 Apr 15 1997 12:00AM 15 Apr, 1997 Apr 15 1997 12:00AM 15 1997 apr Apr 15 1997 12:00AM 1997 apr 15 Apr 15 1997 12:00AM 1997 apr 15 Apr 15 1997 12:00AM

년월일을 구분하는 구분자를 사용하는 set dateformat을 이용할 수 있다1> set dateformat ymd2> go1> insert into abcdef values ('3/5/6')2> go(1 row affected)1> select * from abcdef2> go col1 -------------------------- May 6 2003 12:00AM

1> set dateformat mdy2> go1> insert into abcdef values ('3/5/6')2> go(1 row affected)1> select * from abcdef2> go col1 --------------------------Mar 5 2006 12:00AM

시간시간 넣는넣는 방법은방법은?? 시간을 인식하는 방법은 colon 또는 AM 또는 PM 이 있어야 한다 순서는 시분초 와 milisecond 로 넣어야 한다

1> select col1,convert(char(30),col2,109) from TIME_TAB2> go col1 ------------------------------ ------------------------------ 14:30 Jan 1 1900 2:30:00:000PM 14:30:20:999 Jan 1 1900 2:30:20:996PM 2pm Jan 1 1900 2:00:00:000PM 2 pm Jan 1 1900 2:00:00:000PM 2:30:20:999 pm Jan 1 1900 2:30:20:996PM

6.escape & wildcard 7.set

교보자동차보험 IT 팀 작성일 2002/01/25

Page 135: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

운영자매뉴얼 Veritas Cluster Server V 1.0

8.Isolation level8.Isolation level 수많은 트랜잭션에 의해 데이터는 끊임없이 변경 및 ACCESS 되고 있으며 이러한 과정 속에 검색되는 데이터 값의 어디까지를 내 트랜잭션에서 처리할 것인가를 결정하기 위해 ASE 에서는 isolation level 를 지정할 수 있다isolation 은 다른 트랜잭션에 의해 변경되고 있는 dirty page 를 읽을 수 있는가? 하나의 트랜잭션에서 검색되는 데이터의 일관성을 유지할 것인가? 하나의 트랜잭션에서 발생되는 phantom 현상을 허용할 것인가에 따라 isolation 의 level 을 1,2,3 으로 정의한다

dirty read? nonrepeatable read? phatom read? isolation level? isolation 설정 방법? nonrepeatable 발생을 해결하려면? phantom read 발생을 해결하려면?

Dirty Read?Dirty Read?

트랜잭션 1 이 데이터를 변경후 트랜잭션을 종료(commit 또는 rollback)하지 않은 상태에서 트랜잭션 2 가 변경된 데이터로 접근할 수 있다 트랜잭션 1 이 변경한 데이터에 대해서 commit 할 지 rollback 할지 트랜잭션 2 는 알 수 없으므로 rollback 과 함께 트랜잭션 1 이 종료한다면 트랜잭션 2 는 잘못된 데이터로부터 잘못된 처리를 할 수 있는 위험이 있다 이와 같이 업무 성격에 따라 Dirty Page 를 다른 트랜잭션이 접근하는 것을 허용할 것인지, 안할 것인지에 따라 ioslation 0(허용)와 isolation 1(허용 안함)로 정의 할 수 있다

Nonrepeatable Read?Nonrepeatable Read?

교보자동차보험 IT 팀 작성일 2002/01/25

Page 136: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

운영자매뉴얼 Veritas Cluster Server V 1.0

교보자동차보험 IT 팀 작성일 2002/01/25

Page 137: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

운영자매뉴얼 Veritas Cluster Server V 1.0

트랜잭션 1 이 select 하고 있는 테이블에는 Shared lock 이 걸려 있으므로 트랜잭션이는 트랜잭션 1 이 검색했던 페이지의 데이터를 Modify 한 후 트랜잭션 2 를 종료(commit)할 수 있다. 이때 아직 트랜잭션을 종료하지 않은 트랜잭션 1 이 먼저 select 한 데이터를 다시 검색했을때 같은 트랜잭션에서 같은 질의가 발생했음에도 불구하고 다른 데이터 값을 가져올 수 있다 이와 같이 동일한 트랜잭션에서 동일한 질의에 대해 검색되는 데이터 값에 대한 일관성을 유지할 것인가(isolation level 2), 아니면 유지하지 않을 것인가 (isolation level 1)에 따라 isolation level 을 지정할 수 있다

Phantom Read?Phantom Read?

트랜잭션 1 이 질의를 발생하여 조건에 맞는 row 의 sets 을 검색중인 상황에서 트랜잭션 2 가 같은 테이블의 다른 row 의 sets(트랜잭션 1 이 검색하고 있지 않는 row 의 sets)의 데이터 값을 변경한 후 트랜잭션을 종료 했다트랜잭션 2 가 변경한 데이터 값이 우연히도 트랜잭션 1 의 조건절에 영향을 주는 데이터 값이라 아직 트랜잭션을 종료하지 않은 트랜잭션 1 이 동일한 질의를 실행시켰을 경우 처음 데이터보다 많은 rows 의 set을 검색하게 된다이와 같이 같은 트랜잭션에서 동일한 질의를 발생시켰을 때 더 많은 rows 의 sets 을 보게 되는 현상을 phantom 현상이라 한다 이와 같이 같은 트랜잭션에서 phantom 현상을 허용할 것인지(isolation level 2) 허용하지 않을 것인지(isolation level 3)에 따라 isolation level 을 정의할 수 있다

Isolation Level?Isolation Level? 위의 세가지 현상을 허용할 것인지 허용하지 않을 것인지에 따라 isolation level 을 4 가지로 나눌 수 있으며 level 이 높아질수록 더 많은 제약을 부여한다

Dirty Read Nonrepeatable Read Phantom ReadLevel 0 Allowed Allowed AllowedLevel 1 Prevented Allowed AllowedLevel 2 Prevented Prevented AllowedLevel 3 Prevented Prevented Prevented

Level 0 변경되고 있는 데이터에 대한 정보를 실시간 보기 위한 노력으로 set transaction isolation level 0 명령에 의해 설정되며 select 명령 실행 시 share page lock 을 필요로 하지 않는다Page read 시에 해당 page 에 대한 어떠한 lock 도 장해가 되지 않으며 select 문장의 holdlock option 또한 아무런 효과가 없다현재 다른 트랜잭션에 의해 변경중인(exclusive page lock)page 에 대해서도 read 가 가능하다

Level 1isql 에서 default mode 로 사용되며 select 시 읽혀지는 page 에 대해 순간적으로 Shared Page Lock 이 걸리며 교보자동차보험 IT 팀 작성일 2002/01/25

Page 138: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

운영자매뉴얼 Veritas Cluster Server V 1.0

읽힌 후 바로 Lock 이 해제된다select 문장에서 holdlock option 을 주게 되면 page 를 읽을 때 부여되는 Shared Page Lock 이 바로 해제가 되지 않으며 commit/rollback 명령에 의해서만 해제된다

Level 2같은 트랜잭션에서의 동일한 질의에 대해 동일한 결과 값을 보장해주기 위한 노력으로 select 시 발생한 Shared Lock 은 트랜잭션이 종료(commit or rollback)될 때까지 해제되지 않는다Datarows lock scheme 에서만 지원되며 같은 트랜잭션에서 동일한 질의에 대해 Phantom 현상을 허용한다 Level 3실행되는 모든 select 문에 대해 holdlock option 을 준 효과를 가진다따라서 트랜잭션이 종료(commit/rollback)되기 전까지는 read 된 모든 page 에 대해서 shared page lock 이 해제 되지 않으므로 수많은 lock 을 발생시킬 수 있으므로 주의해야 한다

IsolationIsolation 의의 설정설정 방법방법?? Syntax for Session-Level Isolation:

set transaction isolation level {0 | read uncommitted |1 | read committed |2 | repeatable read |3 | serializable }

Syntax for Statement-Level Isolation:select ...at isolation {0 | read uncommitted |1 | read committed |2 | read repeatable |3 | serializable }

@@isolation returns the isolation level for the session

nonrepeatable nonrepeatable 발생발생 해결하려면해결하려면?? isolation level 을 2,3 으로 올려야 한다예)현재의 isolation level 은 1 이고, 여러 page 를 차지하는 table 을 만든다

교보자동차보험 IT 팀 작성일 2002/01/25

Page 139: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

운영자매뉴얼 Veritas Cluster Server V 1.0

1> use sybsystemprocs2> go1> create table testTABLE (2> a char(255),3> b char(255),4> c char(255),5> d char(255))6> go

1> insert into testTABLE values ('1','1','1','1')2> insert into testTABLE values ('2','2','2','2')3> insert into testTABLE values ('3','3','3','3')4> insert into testTABLE values ('4','4','4','4')5> insert into testTABLE values ('5','5','5','5')6> insert into testTABLE values ('6','6','6','6')7> insert into testTABLE values ('7','7','7','7')8> insert into testTABLE values ('8','8','8','8')9> insert into testTABLE values ('9','9','9','9')10> insert into testTABLE values ('10','10','10','10')11> insert into testTABLE values ('11','11','11','11')12> insert into testTABLE values ('12','12','12','12')13> insert into testTABLE values ('13','13','13','13')14> insert into testTABLE values ('14','14','14','14')15> insert into testTABLE values ('15','15','15','15')16> insert into testTABLE values ('16','16','16','16')17> insert into testTABLE values ('17','17','17','17')18> insert into testTABLE values ('18','18','18','18')19> insert into testTABLE values ('19','19','19','19')20> insert into testTABLE values ('20','20','20','20')21> go

1> select @@isolation2> go ----------- 1

지금부터는 2 개의 session A,B 를 함께 사용해서 하십시요 ************* session A*************1> select @@isolation2> go

----------- 1

1> -- (1) transaction 을 시작한다2> begin tran3> go1> ---(3) a='1' 인 내용을 select 한다. lock 은 읽는 순간에만 걸린다2> select * from testTABLE where a = '1'3> go a b c d ------------------------------------------------------------------------------- 1 1 1 11> ---(6) 위에서 select 한 내용을 똑같이 시도한다.-- 그러나, 한 transaction 안에서도 값은 위의 select 와 똑같지 않다-- 이것이 바로 nonrepeatable read 이다2> select * from testTABLE where a = '1'3> go a b c d ------------------------------------------------------------------------------- 1 1 1 1231> ---(7)교보자동차보험 IT 팀 작성일 2002/01/25

Page 140: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

운영자매뉴얼 Veritas Cluster Server V 1.0

2> commit tran3> go

************* session B*************1> -- (2) transaction 을 시작한다2> begin tran3> go1> -- (4) session A 에서 읽었던 a='1' 인 내용을 update 한다. -- lock 은 execluseve 로 commit tran 을 만날때 까지 풀리지 않는다2> update testTABLE set d = '123' where a = '1'3> go1> ---(5) commit 을 하면, 위의 update 로 인한 lock 이 풀리고-- 다른 session 에서 update 의 변경값을 읽을 수 있다2> commit tran3> go

위의 것은 Isolation level 1 인 경우입니다. Isolation level 2 로 바꾸고 하면 (3)번이 lock 을 걸어 (4)번 수행이 되지 않습니다. 그래서 (6)번,(7)번 수행하고 lock 이 풀려야 (4)번 수행됩니다이처럼 Isolation level 2 에서는 한 transaction 이 1 row 를 읽은 것이 transaction 이 끝날 때 까지 lock 을 걸어 수행이 같은 transaction 에서 그 1 row 를 다시 읽어도 같은 내용이 읽힙니다

phantom read phantom read 발생발생 해결하려면해결하려면?? isolation level 3 으로 해결할 수 있습니다예)현재의 isolation level 은 1 이고, 여러 page 를 차지하는 table 을 만든다

1> use sybsystemprocs2> go1> create table testTABLE (2> a char(255),3> b char(255),4> c char(255),5> d char(255)) lock datarows6> go

1> set transaction isolation level 32> go

1> insert into testTABLE values ('1','1','1','1')2> insert into testTABLE values ('2','2','2','2')3> insert into testTABLE values ('3','3','3','3')4> insert into testTABLE values ('4','4','4','4')5> insert into testTABLE values ('5','5','5','5')6> insert into testTABLE values ('6','6','6','6')7> insert into testTABLE values ('7','7','7','7')8> insert into testTABLE values ('8','8','8','8')9> insert into testTABLE values ('9','9','9','9')10> insert into testTABLE values ('10','10','10','10')11> insert into testTABLE values ('11','11','11','11')12> insert into testTABLE values ('12','12','12','12')13> insert into testTABLE values ('13','13','13','13')14> insert into testTABLE values ('14','14','14','14')15> insert into testTABLE values ('15','15','15','15')16> insert into testTABLE values ('16','16','16','16')17> insert into testTABLE values ('17','17','17','17')

교보자동차보험 IT 팀 작성일 2002/01/25

Page 141: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

운영자매뉴얼 Veritas Cluster Server V 1.0

18> insert into testTABLE values ('18','18','18','18')19> insert into testTABLE values ('19','19','19','19')20> insert into testTABLE values ('20','20','20','20')21> go

지금부터는 2 개의 session A, B 를 함께 사용해서 하십시요

************* session A*************1> -- (1) 현재 isolation level 은 2 입니다1> select @@isolation2> go ----------- 22> begin tran -- transaction 을 시작 합니다3> go1> ---(3) 조건 < 9 인 내용을 보았습니다2> select * from testTABLE where convert(int,a) < 93> goa

----------------------------------------------------------------------- 1 2 3 4 5 6 7 81> ---(6) 조건 < 9 인 내용을 보았습니다 -- session B 의 영향으로 -- 위의 select 결과로 보이지 않던 0 가 보인는 phantom 현상이 발생했습니다2> select * from testTABLE where convert(int,a) < 93> goa ----------------------------------------------------------------------- 1 2 3 4 5 6 7 8 0 1> ---(7)2> commit tran3> go

************* session B*************1> -- (2) 번호순 대로 수행하세요2> begin tran3> go1> -- (4)2> insert into testTABLE values ('0','0','0','0')3> go1> ---(5)

교보자동차보험 IT 팀 작성일 2002/01/25

Page 142: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

운영자매뉴얼 Veritas Cluster Server V 1.0

2> commit tran3> go

위의 것은 Isolation level 2 인 경우이다Isolation level 2 인 경우, 번호순서대로 수행이 가능하나 Isolation level 3 로 바꾸고 하시면 (3)번이 lock 을 걸어 (4)번 수행이 되지 않는다그래서 (6)번,(7)번 수행하고 lock 이 풀려야 (4)번 수행된다

교보자동차보험 IT 팀 작성일 2002/01/25

Page 143: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

운영자매뉴얼 Veritas Cluster Server V 1.0

9.KEY9.KEY ASE 에서 KEY 란? KEY 와 INDEX 관계는? sp_primarykey ? sp_foreignkey ? sp_commonkey ?

ASEASE 에서에서 KEYKEY 란란??ASE 는 DATABASE 설계를 위한 logical key 의 정의를 가능하게 했다그러나, 키 정의는 문서화의 목적만을 위한 것이다.이외의 다른 목적으로 사용되고 있지 않다

KEYKEY 와와 INDEX INDEX 관계는관계는??

키와 인덱스를 혼동하는 경우가 있는데키는 논리적인 데이터베이스 설계자들에게 의미를 갖는 논리적인 엔트리이고인덱스는 물리적인 데이터베이스 객체이고, 그 목적은 퍼포먼스 이다

sp_primarykey ?sp_primarykey ?

sp_primarykey TableName, COL1, COL2, ...primary key - 유일한 행 식별자로 null 을 허용하지 않는다

1> create table TEST_TAB ( col1 int, col2 int, col3 int)2> go1> sp_primarykey TEST_TAB,col12> goNew primary key added.(return status = 0)1> sp_helpkey TEST_TAB2> goFor information on declarative integrity features : PRIMARY KEY, UNIQUE, FOREIGNKEY, CHECK CONSTRAINT, REFERENTIAL CONSTRAINT, NULL/NOT NULL, and DEFAULT, usesp_helpconstraint, a new system stored procedure.

keytype object related_object object_keys related_keys ---------- ------------------------------ ------------------------------ ---------------------------------------------------------------------- ---------------------------------------------------------------------- primary TEST_TAB -- none -- col1, *, *, *, *, *, *, * *, *, *, *, *, *, *, *

(1 row affected)(return status = 0)

TEST_TAB 에 primarykey 를 만들었어도 해당 column 의 unique 를 강요할 수는 없다

교보자동차보험 IT 팀 작성일 2002/01/25

Page 144: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

운영자매뉴얼 Veritas Cluster Server V 1.0

1> insert into TEST_TAB values (1,1,1)2> insert into TEST_TAB values (1,2,2)3> go(1 row affected)(1 row affected)1> sp_helpkey TEST_TAB2> goFor information on declarative integrity features : PRIMARY KEY, UNIQUE, FOREIGNKEY, CHECK CONSTRAINT, REFERENTIAL CONSTRAINT, NULL/NOT NULL, and DEFAULT, usesp_helpconstraint, a new system stored procedure.

keytype object related_object object_keys related_keys ---------- ------------------------------ ------------------------------ ---------------------------------------------------------------------- ---------------------------------------------------------------------- primary TEST_TAB -- none -- col1, *, *, *, *, *, *, * *, *, *, *, *, *, *, * foreign TEST_TAB2 TEST_TAB col1, *, *, *, *, *, *, * col1, *, *, *, *, *, *, *

sp_foreignkey ?sp_foreignkey ? sp_foreignkey TableName,pk_table_name, col1, col2..foreign key - 다른 테이블의 기본 키이며, 일반적으로 조인을 위해 사용된다

1> sp_foreignkey TEST_TAB2,TEST_TAB,col12> goNew foreign key added.(return status = 0)

1> sp_helpkey TEST_TAB22> goFor information on declarative integrity features : PRIMARY KEY, UNIQUE, FOREIGNKEY, CHECK CONSTRAINT, REFERENTIAL CONSTRAINT, NULL/NOT NULL, and DEFAULT, usesp_helpconstraint, a new system stored procedure.

keytype object related_object object_keys related_keys ---------- ------------------------------ ------------------------------ ---------------------------------------------------------------------- ---------------------------------------------------------------------- common TEST_TAB2 TEST_TAB3 col1, *, *, *, *, *, *, * col1, *, *, *, *, *, *, * foreign TEST_TAB2 TEST_TAB col1, *, *, *, *, *, *, * col1, *, *, *, *, *, *, *

(2 rows affected)(return status = 0)

sp_commonkey ?sp_commonkey ? sp_commonkey TableName1,TableName2, col1a,col2a,colb1,colb2,...common key - 일반적으로 alternate 보다 짧은 기본키. 조인을 위해 사용됨

1> sp_helpkey TEST_TAB32> go교보자동차보험 IT 팀 작성일 2002/01/25

Page 145: 새로운 시스템 Decomposition · Web viewtablename : Proxy table로 생성할local table. objectdef : 외부 Object의 저장위치. objecttype : view, table, rpc. STEP 2) Proxy

운영자매뉴얼 Veritas Cluster Server V 1.0

For information on declarative integrity features : PRIMARY KEY, UNIQUE, FOREIGNKEY, CHECK CONSTRAINT, REFERENTIAL CONSTRAINT, NULL/NOT NULL, and DEFAULT, usesp_helpconstraint, a new system stored procedure.

keytype object related_object object_keys related_keys ---------- ------------------------------ ------------------------------ ---------------------------------------------------------------------- ---------------------------------------------------------------------- common TEST_TAB2 TEST_TAB3 col1, *, *, *, *, *, *, * col1, *, *, *, *, *, *, *

(1 row affected)(return status = 0)

10.sql 문장

11.dynamic sql

교보자동차보험 IT 팀 작성일 2002/01/25