ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드...

151
ASE Programming Guide for Oracle programmers SYBASE SYBASE PRESALES Project: PowerTrack Code Document ID: doc_id Status: Draft Caveat: Sybase Presales Version No: 0.1 Version Date: 22 Aug 2006

Transcript of ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드...

Page 1: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

ASE Programming Guide for

Oracle programmers

SYBASE SYBASE PRESALES

Project: PowerTrack Code Document ID: doc_id Status: Draft Caveat: Sybase Presales Version No: 0.1

Version Date: 22 Aug 2006

Page 2: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

Document History Template Version: 3.5, 13-Sep-98

Version Date Author Comment Authorization

0.1 22 Aug 2006 한상욱

Adaptive Server Enterprise15.0 Version: 0.1, 22 Aug 2006

Page 3: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

Table of Contents 1. 개요..............................................................................................................................1

1.1 목적 ................................................................................................................1

1.2 누구를 위한 것인가 ......................................................................................1

1.3 Scope ..............................................................................................................1

1.4 Copyright ........................................................................................................1

1.5 Distribution.....................................................................................................1

2. 기본 구조의 비교 ........................................................................................................2

2.1 Engine 구조 ....................................................................................................2

2.2 메모리 구조 ...................................................................................................3

3. SQL 의 차이................................................................................................................5

3.1 SQL 이 왜 중요한가 ......................................................................................5

3.2 SQL 의 비교 ...................................................................................................5

3.2.1 T-SQL : PLSQL..............................................................................................5

3.2.2 Built-in Functions .........................................................................................11

4. Transaction Mode ....................................................................................................14

4.1 Chain mode 와 unchain mode 의 차이.........................................................14

4.1.1 Unchained mode ...........................................................................................14

4.1.2 Chained mode ...............................................................................................14

4.2 Transaction mode 확인 방법 .......................................................................14

4.3 Transaction mode 설정 방법........................................................................14

4.4 Chain mode 와 Unchain mode 예 ................................................................15

5. Lock...........................................................................................................................17

5.1 Lock 발생하는 이유 ....................................................................................17

5.2 Lock 의 발생과 해제 ...................................................................................17

5.3 Holdlock 이란...............................................................................................17

5.4 언제 holdlock 을 사용하는가? ...................................................................18

5.5 isolation Level ................................................................................................2

5.6 Lock 탐지방법 ...............................................................................................3

5.7 Lock wait ........................................................................................................4

5.8 Table Lock Scheme ........................................................................................5

6. Deadlock......................................................................................................................6

6.1 ASE 에서 deadlock 처리 ...............................................................................6

6.2 Deadlock 방지법 ............................................................................................6

6.3 Deallock 탐지 .................................................................................................6

7. Data Type....................................................................................................................8

7.1 ASE Data type ................................................................................................8

Adaptive Server Enterprise15.0 Page i Version: 0.1, 22 Aug 2006

Page 4: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

7.2 데이터 타입 선언 ..........................................................................................8

7.2.1 테이블의 열에 대한 데이터 유형 선언 .......................................................8

7.2.2 배치 및 프로시저 에서 로컬 변수 선언 ......................................................8

7.2.3 Stored Procedure 에서 매개 변수 형 선언....................................................9

7.3 데이터 타입 변환 ..........................................................................................9

7.4 공백처리 ......................................................................................................10

7.5 NULL 사용...................................................................................................11

7.5.1 기본 지침 .....................................................................................................11

7.5.2 Null 허용 칼럼의 정의 ................................................................................11

7.5.3 Null 사용 시 프로그래밍 ............................................................................12

7.6 기타 지침 .....................................................................................................13

7.7 데이터 Type 비교 ........................................................................................13

8. 테이블 과 데이터 접근 .............................................................................................16

8.1 오브젝트 비교 .............................................................................................16

8.2 테이블 목록 확인 ........................................................................................16

8.3 테이블 접근 .................................................................................................17

8.4 Computed column.........................................................................................17

8.4.1 유리한 점 .....................................................................................................17

8.4.2 데이터 materialization 옵션 ........................................................................18

8.5 Function based index ....................................................................................20

8.6 Derived Table(in-line view) .........................................................................21

8.6.1 특징 ..............................................................................................................21

8.6.2 장점 ..............................................................................................................21

8.6.3 사용 예 .........................................................................................................22

8.6.4 구현 시 주의사항 ........................................................................................22

9. Partition ....................................................................................................................25

9.1 Partition 의 종류...........................................................................................25

9.2 Range partition .............................................................................................25

9.2.1 언제 사용하는가 .........................................................................................26

9.2.2 구현 예 .........................................................................................................26

9.3 Hash Partition ...............................................................................................27

9.3.1 언제 사용하는가 .........................................................................................27

9.3.2 구현 예 .........................................................................................................28

9.4 List Partition .................................................................................................28

9.4.1 언제 사용하는가 .........................................................................................28

9.4.2 구현 예 .........................................................................................................29

9.5 Round Robin.................................................................................................29

9.5.1 언제 사용하는가 .........................................................................................29

9.5.2 구현 예 .........................................................................................................30

9.6 Partition Index ..............................................................................................30

9.6.1 Global Index .................................................................................................30

Adaptive Server Enterprise15.0 Page ii Version: 0.1, 22 Aug 2006

Page 5: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

9.6.2 Clustered Local Index...................................................................................31

9.6.3 Non Clustered Local Index...........................................................................31

9.7 partition key rule...........................................................................................32

9.8 Partitioning 효과 ..........................................................................................32

10. Stored Procedure ........................................................................................33

10.1 Stored Procedure 를 권고 하는 이유...........................................................33

10.2 Stored Procedure 생성 예.............................................................................33

10.3 에러 핸들링 .................................................................................................34

10.4 Stored Procedure 와 Transaction mode ........................................................37

10.5 Compile ........................................................................................................39

10.6 Stored Procedure 구현 시 지침....................................................................39

11. OLTP 프로그램...........................................................................................42

11.1 Multi-rows 조회 ...........................................................................................42

11.2 기타 OLTP 구현 지침 .................................................................................46

11.2.1 Query 구현 ............................................................................................46

11.2.2 Operator 사용 ........................................................................................53

11.2.3 Index 사용 .............................................................................................54

11.2.4 데이터 타입 사용 .................................................................................57

11.2.5 Transaction ............................................................................................57

12. Batch 프로그램............................................................................................58

12.1 Stored Procedure 활용..................................................................................58

12.2 Cursor 사용 ..................................................................................................58

12.2.1 Non scrollable Cursor............................................................................58

12.2.2 Scrollable cursor ....................................................................................59

12.2.3 Sensitivity in Cursor ..............................................................................59

12.2.4 Cursor 구현 지침 ..................................................................................59

12.3 기타 배치 지침 ............................................................................................62

13. Online-Batch 프로그램...............................................................................64

13.1 구현 지침 .....................................................................................................64

14. 원격 데이터 접근.........................................................................................65

14.1 Component Integration Service 란 ...............................................................65

14.1.1 Proxy Table 생성...................................................................................65

14.1.2 Remote Procedure call...........................................................................66

14.1.3 외부 파일 접근 .....................................................................................67

14.1.4 CIS 구현 지침 .......................................................................................67

14.2 Multi-connection 연결 .................................................................................68

14.2.1 ESQL/C 에서 구현 예 ..........................................................................68

14.2.2 Multi connection 구현 시 주의사항.....................................................70

Adaptive Server Enterprise15.0 Page iii Version: 0.1, 22 Aug 2006

Page 6: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

15. Optimization................................................................................................71

15.1 Optimization Goals.......................................................................................71

15.2 Goals 선택방법 ............................................................................................71

15.3 Join 의 종류..................................................................................................72

15.3.1 Nested Loop Join ...................................................................................72

15.3.2 Merge Join .............................................................................................72

15.3.3 Hash Join ...............................................................................................73

16. Adaptive Server Enterprise 접근하기 ......................................................74

16.1 ASE 접근하기 위한 환경............................................................................74

16.2 isql 사용하기 ...............................................................................................74

16.3 Bcp 사용 데이터 추출/적재........................................................................76

17. Tools .............................................................................................................78

17.1 Sybase Central ..............................................................................................78

17.2 ODBC 설정 ..................................................................................................78

17.3 Interactive SQL.............................................................................................80

17.4 Plan viewer ...................................................................................................80

18. ASE New features .......................................................................................82

18.1 12.5 에서의 변경 내용 ................................................................................82

18.1.1 외부 파일 시스템 지원 .......................................................................82

18.1.2 뷰에서 Union 지원 ...............................................................................82

18.2 12.5.0.1 에서의 변경 내용 ..........................................................................82

18.2.1 insert 문을 통한 file 과 directory 생성 지원......................................82

18.3 12.5.0.3 에서의 변경 내용 ..........................................................................83

18.3.1 len 함수 .................................................................................................83

18.3.2 left 함수 .................................................................................................83

18.3.3 square 함수 ............................................................................................84

18.3.4 str_replace 함수.....................................................................................84

18.3.5 year, month, day 함수 ...........................................................................85

18.3.6 newid 함수.............................................................................................85

18.4 12.5.1 에서의 변경 내용 .............................................................................86

18.4.1 SQL Derived Table ( Inline-View)........................................................86

18.4.2 current_date, curreut_time 함수 ............................................................86

18.5 12.5.3 에서의 변경 내용 .............................................................................87

18.5.1 top n 기능 ..............................................................................................87

18.5.2 identity 를 사용할 수 있는 type 추가 ..................................................88

18.6 15.0 에서의 변경 내용 ................................................................................88

18.6.1 scrollable cursor.....................................................................................88

18.6.2 insensitive cursor ...................................................................................89

18.6.3 computed column ..................................................................................89

18.6.4 function based index..............................................................................90

Adaptive Server Enterprise15.0 Page iv Version: 0.1, 22 Aug 2006

Page 7: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

18.6.5 identity 를 사용할 수 있는 type 추가 ..................................................90

18.6.6 Optimizer 변경 ......................................................................................90

18.6.7 GUI Based Plan Viewer 변경 ...............................................................90

18.6.8 Table Partitioning ..................................................................................91

18.7 15.0.1 에서의 변경 내용 .............................................................................91

18.7.1 isdate 함수.............................................................................................91

18.7.2 isnumeric 함수 ......................................................................................91

19. Sybase ASE 기본 Syntax ............................................................................93

19.1 필수 Utility...................................................................................................93

19.1.1 isql 사용 방법 .......................................................................................93

19.1.2 bcp 사용 방법 .......................................................................................93

19.2 기본 Command.............................................................................................93

19.2.1 표기법 ...................................................................................................93

19.2.2 개요 .......................................................................................................94

19.2.3 alter table ...............................................................................................96

19.2.4 begin … end...........................................................................................97

19.2.5 begin transaction....................................................................................98

19.2.6 break ......................................................................................................98

19.2.7 case ........................................................................................................99

19.2.8 close .....................................................................................................100

19.2.9 commit .................................................................................................100

19.2.10 continue ...............................................................................................101

19.2.11 create index..........................................................................................102

19.2.12 create procedure...................................................................................103

19.2.13 create table...........................................................................................103

19.2.14 create trigger ........................................................................................104

19.2.15 create view...........................................................................................105

19.2.16 deallocate cursor ..................................................................................105

19.2.17 declare..................................................................................................106

19.2.18 declare cursor.......................................................................................106

19.2.19 delete....................................................................................................107

19.2.20 drop index............................................................................................108

19.2.21 drop procedure.....................................................................................108

19.2.22 drop table .............................................................................................108

19.2.23 drop trigger ..........................................................................................109

19.2.24 drop view .............................................................................................109

19.2.25 execute .................................................................................................109

19.2.26 fetch .....................................................................................................110

19.2.27 goto Label ............................................................................................111

19.2.28 if …. else..............................................................................................111

19.2.29 insert ....................................................................................................112

19.2.30 open .....................................................................................................112

19.2.31 raiserror................................................................................................113

19.2.32 return....................................................................................................113

Adaptive Server Enterprise15.0 Page v Version: 0.1, 22 Aug 2006

Page 8: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

19.2.33 rollback ................................................................................................114

19.2.34 select ....................................................................................................115

19.2.35 set.........................................................................................................115

19.2.36 truncate table........................................................................................117

19.2.37 unoin 연산자 .......................................................................................117

19.2.38 update...................................................................................................118

19.2.39 while ....................................................................................................119

19.3 기본 Built-in Function................................................................................120

19.3.1 개요 .....................................................................................................120

19.3.2 사용법 .................................................................................................122

Adaptive Server Enterprise15.0 Page vi Version: 0.1, 22 Aug 2006

Page 9: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

1. 개요

1.1 목적 본 문서는 SYBASE Adaptive Server Enterprise 를 처음 접해보는 개발자들이 보다 효과적으로 SYBASE Adaptive Server Enterprise 를 사용하여 응용 프로그램을 작성할 수 있도록 하기 위하여 작성된 문서 입니다.

1.2 누구를 위한 것인가 본 문서는 타 데이터베이스에 대해서는 상당한 지식을 가지고 있으나 SYBASE Adaptive Server Enterprise 는 처음인 프로그래머들을 위한 기본 프로그램 지침서 입니다. 즉:

타 RDBMS 의 원리에 대해서 매우 견고한 지식을 가지고 있거나

일반적인 데이터베이스 관리 지식을 갖추고 있거나

타 DB 에서 제공하는 SQL 혹은 ANSI SQL 언어에 익숙해 있는 프로그래머 거나

DB 관리자 책임을 하고 계시는 분들을 위한 가이드 입니다

1.3 Scope 본 문서는 T-SQL 을 사용하여 효과적으로 프로그래밍 하기 위한 방법을 제공 하지만 구체적인 SQL 문법을 제공하지는 않습니다.

1.4 Copyright 본 문서는 Sybase 전문 기술부에 귀속되며 전체 혹은 일부가 Sybase 전문 기술부 동의 없이 복제되어 사용될 수 없습니다.

1.5 Distribution 본 문서는 Sybase 전문 기술부가 작성하여 업무에 해당하는 스텝과 본 작업과 유사한 일을 수행하는 Sybase 컨설턴트에 배포 합니다.

Adaptive Server Enterprise15.0 Page: 1 Version: 0.1, 22 Aug 2006

Page 10: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

2. 기본 구조의 비교

2.1 Engine 구조

Oracle 에서는 데이터베이스를 다음과 같은 요소들을 포함한 전체 Oracle RDBMS 환경을 이야기 한다.

Table spaces

System table space

Table spaces

System table space Master DB를 포함한시스템 DB

Users DB & log

Master DB를 포함한시스템 DB

Users DB & log

Oracle 데이터베이스 프로세스와 버퍼들(instance).

하나 이상의 데이터 파일로 구성되어 있고 하나로 중앙 집중화 된 시스템 카탈로그를 포함하고 있는 SYSTEM 테이블 영역.

하나 이상의 데이터 파일로 구성되어 있는 DBA 가 정의한 다른 테이블 영역.

둘 혹은 그 이상의 온라인 Redo Logs.

Archived Redo Logs (optional).

Miscellaneous other files (control file, Init.ora, config.ora 등).

Adaptive Server Enterprise 는 다중 데이터베이스 환경을 제공합니다. 즉 Adaptive Server Enterprise 를 사용한 어플리케이션들은 논리적으로 업무기능에 따라 분리된 데이터베이스를 사용할 수 있으며, 이 것은 하나의 컴퓨터에서 Adaptive Server Enterprise 가 다중의 instance 를 가질 수 있다는 것을 의미합니다. 또 Adaptive Server Enterprise 각 instance 들은 다중의 데이터베이스를 가질 수 있습니다. 각 database 는 물리적인 데이터의 저장소로 서 한 개 혹은 n 개의 디바이스를 갖습니다. 또한 각 데이터베이스 디바이스들의 논리적인 저장소로서 segment 단위의 관리를 지원합니다.

Adaptive Server Enterprise 는 설치와 함께 다음과 같은 데이터베이스를 기본적으로 가지게 됩니다.

Master 데이터베이스 : Adaptive Server Enterprise 의 가장 핵심적인 정보를 보관하고 있는 시스템 데이터베이스.사용자 DB 정보, 로그인 정보, 디바이스 정보, role 에 관한 정보, 원격서버에 관한 정보,

Adaptive Server Enterprise15.0 Page: 2 Version: 0.1, 22 Aug 2006

Page 11: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

원격서버 로그인 정보 등…(Oracle 의 control file 과 유사한 정보를 가지고 있습니다)

Model 데이터 베이스 : 새로운 데이터베이스를 생성할 때 template 이 되는 시스템 데이터베이스.

Tempdb : Oracle temporary tablespace 와 유사한 기능을 하는

데이터베이스로 sort, merge, count, max, min 등 의 work area 로

사용되는 임시 데이터베이스.

Sybsystemprocs : Adaptive Server Enterprise 명령어의 대부분이 stored procedure 로 구성되어 있는데 이 system stored procedures 가

저장되어 있는 데이터베이스.

Sybsystemdb : 2PC transactions 의 recovery 를 담당하는 시스템

데이터베이스.

2.2 메모리 구조

Oracle 은 메모리 영역을 SGA (Shared Global Area) 라 부른다. 여기에는 아래와 같은 각각의 캐시 영역들이 있다.

Library cache : 문자의 텍스트 및 Parse Tree 정보와 실행계획 저장

Data Dictionary Cache : Database 에 존재하는 테이블과 뷰의 이름, 테이블에 있는 각 칼럼의 이름과 datatype 등을 저장

Database buffer cache : 디스크로부터 읽어 들인 데이터 블럭의 복사본이 있는 영역

redo log buffer : 모든 변경 정보들을 저장하고 있는 circular buffer

Adaptive Server Enterprise15.0 Page: 3 Version: 0.1, 22 Aug 2006

Page 12: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

Adaptive Server Enterprise 의 메모리 구조는 위의 그림에서 보는 바와 같습니다. 서버 구성변수에서 memory max 값의 설정에 따라 사용할 공간의 크기가 결정됩니다. 아래의 캐시 영역들이 사용자의 튜닝에 의해서 바뀔 수 있는 공간입니다.

Default Data Cache : 클라이언트의 요구에 의해서 처리되는 모든 작업을 수행하는 메모리 공간을 이야기한다. 즉 데이터베이스의 데이터 페이지, 인덱스 페이지, 로그 등의 내용을 담고 있는 영역.

Named Cache : Physical Disk I/O 를 줄여서 데이터베이스 성능을 높이고자 할 경우 데이터베이스 혹은 특정 오브젝트, 인덱스 등을 바이드 하여 사용할 수 있는 응용이 가능한 메모리 영역.

Procedure Cache : stored procedure , esql/c 등의 어플리케이션에서 사용하는 메모리 영역.

Statement Cache : Ad hoc query 의 성능을 높이기 위해서 query plan 을 저장해 놓는 메모리 영역

Adaptive Server Enterprise15.0 Page: 4 Version: 0.1, 22 Aug 2006

Page 13: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

3. SQL 의 차이

3.1 SQL 이 왜 중요한가 개발자가 직면하는 전환 이슈 중에서 가장 중요한 것은 SQL 표준과 각 RDBMS 가 제공하는 확장된 SQL 언어의 구현이다. 어떤 개발자는 오로지 SQL 표준의 언어만 사용하여 프로그램을 코딩 하려고 합니다. 이 의미는 SQL-표준에 제한을 두자는 것이고 이것은 Oracle, SYBASE 혹은 많은 다른 어떤 데이터베이스 제품에서도 구현할 수 있게 하자는 것 입니다. 이 접근은 프로그램 성능의 문제와 불필요하고 복잡한 프로그램 코드를 만들어 낼 수 있습니다. 그러나 반대로 생각하면 특정 vendor 에 종속적이지 않기 때문에 그 나름대로 장점이 될 수 있습니다. Oracle 의 DECODE 함수는 SQL 표준을 벗어나는 Oracle 만이 가지고 있는 함수입니다. 그리고 사이베이스 ASE 에 있는 CASE 문은 SQL 표준의 확장형 으로 모든 데이터베이스에서 구현 가능하다고 할 수는 없습니다. Oracle 의 DECODE 와 사이베이스 ASE 의 CASE 문 모두 Query 에서 세련된 형태의 조건을 처리할 수 있습니다. 이와 같이 Oracle 의 PLSQL 과 사이베이스의 Transact-SQL 언어는 기능상 유사하나 문법상 틀린 점이 많습니다. 특화 된 개발 인터페이스 또한 추가적인 이슈가 될 수 있습니다. 따라서 어플리케이션을 개발할 경우 다중 RDBMS 에서 사용할 것을 고려하여 표준 인터페이스를 사용하는 것도 고려해야 할 사항 입니다

3.2 SQL 의 비교

3.2.1 T-SQL : PLSQL

# Oracle SYBASE Activity

1 / GO Search and Replace

(S_R) / as GO

2 Semicolon Use

in Oracle SQL

Global replace with a

space.

3 Variable

declaration

e.g x:=

expression;

SELECT @x = expression

Adaptive Server Enterprise15.0 Page: 5 Version: 0.1, 22 Aug 2006

Page 14: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

4 Parameter

Naming

Convention

Translate in Sybase to

preceeding character

@. May cause “length” problems of existing

30 character long

variable

names in existing Oracle

code.

5 select …. INTO

variable

This is the Oracle

convention for

transferring

data value to a variable.

Use the Sybase

syntax - select

@variable1=col1,

@variable2=col2… ad

inf.

Manual

6 CONSTANTS Redefine as

variables and check

scope of usage

(local or global).

7 %TYPE Code manual field definition to replace this.

8 %ROWTYPE Code each field as an

individual variable.

Manual recode.

9 IS RECORD OF Code each field as an

individual variable.

Manual coding

conversion.

10 IS TABLE OF Code as temp table and

use FETCH or

SELECT to process row.

Redesign code to

temp table with

cursor scan

processing.

11 dbms Oracle

calls

Recode to Sybase

functions such as

RAISEERROR or PRINT

and other Sybase

System Stored

Procedures.

Manual recode.

Adaptive Server Enterprise15.0 Page: 6 Version: 0.1, 22 Aug 2006

Page 15: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

12 Dynamic SQL Recode to Sybase T-

SQL. PowerBuilder can

issue SQL dynamically,

but Sybase does not

support robust dynamic

SQL processing.

Manual recode.

13 Using DFAULT

E.g

blood_type

char := ‘O’

Use “=” sign

E.g.

@blood_group char = ‘O’

14 EXIT WHEN

nDbedDone =

1

AND

nAWMSDone =

1;

Convert this to an

expression and a T-SQL

BREAK or RETURN

statement as a part of a

conditional IF statement.

Manual recode.

15 INITCAP Translate to Sybase stored procedures or

Open Client / Open Server applications.

Adaptive Server Enterprise15.0 Page: 7 Version: 0.1, 22 Aug 2006

Page 16: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

16 SEQUENCE or

CREATE

SEQUENCE

E.g CREATE

SEQUENCE

test_seq

MINVALUE 1

STARTWITH 1

INCREMENTED

by 1

CACHE 20;

INSERT INTO

m_table

VALUES

(test.seq.nextv

al,…);

A key table will be set up

and stored

procedures defined to

emulate the NEXTVAL

function in Oracle. The

specs of this is as

follows:

CREATE TABLE my_seq

(seq int)

go

INSERT INTO my_seq

select 0

go

CREATE PROCEDURE

get_seq (@seq int

OUTPUT)

AS

UPDATE my_seq SET seq

= seq+1

SELECT @seq = seq

FROM my_seq

go

DECLARE @seq int

EXEC get_seq @seq

OUTPUT

INSERT INTO m_table

VALUES (@seq,…)

Go

Manual recode. Will

involve

schema changes.

17 synonym Recode manually to the

database.table.column_n

ame, which is to be

referenced for each field

reference.

Manual recode.

18 TYPE

AccountingRec

IS

RECORD

Code each field as an

individual variable.

Manual recode.

Adaptive Server Enterprise15.0 Page: 8 Version: 0.1, 22 Aug 2006

Page 17: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

19 UNION Evaluate UNIONS in

CURSORs and recode.

Note that you cannot use

a UNION

command in the SELECT

statement of an

updatable cursor. There

are also special

conditions for same

number of expressions

in tables of the UNION,

and the order in

which the columns must

appear.

Manual recode.

20 userenv('sessio

nid')

The kernel pid from

master..sysprocesses

identifies the session’s

unique thread id. Use

the following syntax as

an equivalent: select

kpid from

master..sysprocesses

where status

= "running".

Manual recode.

21 VARIABLE

HANDLING -

GLOBAL AND

LOCAL

Local variables may be

used in a procedure

and then their value

passed onto another

called or sub-procedure

or back to a calling

procedure. May involve

special coding for

any Global variables or

variables used in a

package which was

converted into separate

stored procedures.

Manual recode.

Adaptive Server Enterprise15.0 Page: 9 Version: 0.1, 22 Aug 2006

Page 18: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

22 user-defined

functions

Use Sybase Stored

Procedures to pass data

to; to operate on it; and

return it afterwards.

The EXECUTE command

is used to run a

systemprocedure or a

user-defined stored

procedure.

Manual recode.

23 IS In procedure declaration,

translate to AS

S_R selective.

24 NUMBER type

in stored

procedures

use NUMERIC(10)

25 Packages and

Procedures

Private and

Public

Translate packages to

single stored

procedures where

possible, and split into

separate stored

procedures where

necessary.

Manual recode.

26 Triggers

(BEFORE

TRIGGERS)

RULES can be used in

Sybase to specify the

domain of acceptable

values for a particular

column, or for any

column of a user-defined

datatype. Also evaluate

each condition and

possibly use CHECK

integrity constraints

with the CREATE TABLE

statement.

Manual recode.

Adaptive Server Enterprise15.0 Page: 10 Version: 0.1, 22 Aug 2006

Page 19: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

27 RETURN

BOOLEAN

Translate to return an

integer expression

and evaluate in receiving

procedure or

statement. Since Boolean

is not an

integer_expression, it is

not allowed as a

parameter to the Sybase

RETURN parameter.

This will need to be

translated to the integer

expressions (0,1) and

translated when

received for processing.

1=False; 0=True.

Instead of using the

numeric literals 1 or 0,

the two variables should

be defined as

follows: @false integer=1

and @true

interger=0; so that the

stored procedure

should return either

@false or @true.

Manual recode.

3.2.2 Built-in Functions

1 CEIL

Returns the smallest

integer

greater than or

equal to the

specified value

CEILING S_R

2 TRUNC

String functions

CONVERT(INT,..) S_R

3 SUBSTR() SUBSTRING() S_R

4 LENGTH() CHAR_LENGTH() S_R

5 CHR() CHAR() S_R

Adaptive Server Enterprise15.0 Page: 11 Version: 0.1, 22 Aug 2006

Page 20: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

6 TO_CHAR CONVERT Manual

recode.

7 TO_NUMBER CONVERT(NUMERIC(n,n),fiel

d)

Manual

recode.

8 convert_char_to_nu

mber

This is a custom-defined

character to

numeric conversion routine.

It can be

replaced with the Sybase

function

(convert(decimal(x,y),

“string”). For the

purposes of the s2k

applications set x to 18,

and y to 9.

S/R

&Manual

recode.

9 DATE functions and

calculations

Recode to Sybase date

handling routines.

Sybase supports a large

selection of date

and time functions such as

DATEADD,

DATEDIFF, DATEPART(),

DATENAME(),

timestamp and others.

S_R and

manual

recode.

10 LAST_DAY Translate to Sybase stored

procedures or

Open Client / Open Server

applications.

Manual

recode.

11 SYSDATE,

SYSTIMESTAMP

Use Sybase GETDATE() and

proper

formatting functions.

S_R

selective.

12 DATE and

TIMESTAMP

Functions

Replace in some cases

using a local variable,

or it can be re-architected

to use the Sybase

User Defined TIMESTAMP

data type.

Manual

recode.

Adaptive Server Enterprise15.0 Page: 12 Version: 0.1, 22 Aug 2006

Page 21: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

13 TRUNC(dstartdate)

Conditional

functions

Use Sybase CONVERT and

the format that

returns the date at 00:00

hour.

Manual

recode.

14 NVL Translate NVL to ISNULL. S_R

selective.

15 NVL2

E.g

NVL2(salary,salary*2

,0)

CASE structure

E.g. CASE

WHEN salary = NULL THEN 0

ELSE salary * 2

END

16 DECODE Used to

evaluate the

values with ‘if-else’ logic

Convert to Sybase case expression code.

For e.g.

SELECT STUDENT_ID,

(CASE WHEN COURSE_ID = 101 THEN 1

ELSE 0 END) AS COURSE_101,

(CASE WHEN COURSE_ID = 105 THEN 1

ELSE 0 END) AS COURSE_105,

(CASE WHEN COURSE_ID = 201 THEN 1

ELSE 0 END) AS COURSE_201,

(CASE WHEN COURSE_ID = 210 THEN 1

ELSE 0 END) AS COURSE_210,

(CASE WHEN COURSE_ID = 300 THEN 1

ELSE 0 END) AS COURSE_300

GROUP BY STUDENT_ID

ORDER BY STUDENT_ID

Adaptive Server Enterprise15.0 Page: 13 Version: 0.1, 22 Aug 2006

Page 22: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

4. Transaction Mode

4.1 Chain mode 와 unchain mode 의 차이

4.1.1 Unchained mode

Transaction 의 끝에 자동으로 commit 이 됩니다

Transaction 을 수행하기 위해서는 명시적으로 begin tran 명령을 기술하고 commit 또는 rollback 을 명시해야 합니다

4.1.2 Chained mode

묵시적으로 begin tran 을 실행합니다

반드시 commit tran 또는 rollback tran 을 표시해야 합니다

4.2 Transaction mode 확인 방법 select @@tranchained 로 합니다

chained mode 는 1 , unchained mode 는 0 입니다

예)

1> select @@tranchained

2> go

-----------

0

isql 은 unchained mode 이고, ESQL/C 는 chained mode 입니다. 그 밖의 client 개발에 사용되는 tool 도 기본 mode 를 확인 한 뒤 program 해야 합니다

4.3 Transaction mode 설정 방법 set 명령어로

설정 : set chained on

해제 : set chained off

ESQL/C pre compile unchained mode 설정

방법) cpre -r( nohold lock) -m (unchained mode)

ANSI

Adaptive Server Enterprise15.0 Page: 14 Version: 0.1, 22 Aug 2006

Page 23: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

1) chained mode 가 기본 모드입니다

2) commit 이나 rollback 을 수행해야 transaction 이 정상적으로 끝납니다

3) isolation level 3 에서 수행됩니다

Non-ANSI

1) unchained mode 입니다

2) isolation level 1 을 default method 로 사용합니다

3) 자동적으로 commit 을 합니다

4) commit 이나 rollback 을 수행해서 transaction 을 종료하고 싶으면 반드시 begin transaction 으로 transaction 을 시작 해야 합니다

4.4 Chain mode 와 Unchain mode 예 chained mode

1> insert into publishers values ('9999', null, null, null)

2> begin tran => 명령어가 무시됩니다

3> delete from publishers where pub_id = '9999'

4> rollback tran => insert 된 값이 rollback 됩니다

5> 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

1> set chained off

2> go

1> select @@tranchained

2> go

Adaptive Server Enterprise15.0 Page: 15 Version: 0.1, 22 Aug 2006

Page 24: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

-----------

0

(1 row affected)

1> insert into publishers values ('9999', null, null, null) =>자동 commit

2> begin tran

3> delete from publishers where pub_id = '9999'

4> rollback tran => delete 명령이 rollback 합니다

5> 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)

Adaptive Server Enterprise15.0 Page: 16 Version: 0.1, 22 Aug 2006

Page 25: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

5. Lock

5.1 Lock 발생하는 이유 Lock 은 RDBMS 에서 데이터의 일관성을 유지하기 위한 기본적인 mechanism 입니다. 즉 다중 사용자 시스템에서 transaction 을 유지하기 위해서는 쓰기 또는 읽기 중인 데이터에 대한 보호가 되어야 하며 DB engine 은 lock 이라는 mechanism 을 가지고 이러한 일관성을 보장합니다.

현재 사용되고 있는 table, page, row 에 대한 다른 transaction 의 사용 제한을 의미합니다

lock 의 종류에 따라 제한 정도(read 는 가능여부) 가 다릅니다

문제는 lock contention 이라 할 수 있는데, 즉 blocking 을 말합니다

5.2 Lock 의 발생과 해제 SQL 문장이 수행되는 시점에 발생됩니다

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

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

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

5.3 Holdlock 이란 select 문장 실행 시 잡힌 Shared Page Lock 의 해제를 commit 이나 rollback 명령을 통해 풀리게 되는데 보통 조회 후 조회된 결과에 따른 변경(insert, update, delete)을 할 경우에 사용 됩니다. Hold lock option 없이 조회한 경우는 해당 rows 를 읽은 후 바로 Lock 이 해제가 됩니다.

Hold lock option 은 exclusive lock 이 아닌, shared lock 을 잡습니다. 그러므로 select 는 허용하며, insert/update 는 허용되지 않는다.

예)

SELECT * FROM TEST_TAB HOLDLOCK WHERE ID > 100

본 프로젝트에서는 hold lock 사용을 제한 합니다

Adaptive Server Enterprise15.0 Page: 17 Version: 0.1, 22 Aug 2006

Page 26: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

5.4 언제 holdlock 을 사용하는가? 자신의 transaction 에서 select 한 값을 다른 transaction 에 영향 받지 않고, 처리 하고자 하는 경우 hold lock 을 사용합니다.

예)

SELECT Amt INTO :H_Amt

FROM TABLE_A HOLDLOCK where a = H_a;

H_Amt = H_Amt + 1

UPDATE TABLE_A set

이 경우 dead lock 상황을 조심 해야 합니다. 동시 사용자 수가 많고, insert/update/delete 문장이 있는 경우, deadlock 을 조심 해야 합니다. 위 예의 select hold lock 문장(오른쪽)이 동시 다발적으로 수행 된다면 Table_A 의 한 row 를 update 하려고 하지만, 다른 transaction 에서 해당 row 를 shared lock 을 잡고 있으므로, 대기하게 됩니다. 즉, 서로간에 shared lock 을 잡아서 I/U/D 를 할 수 없으므로 교착상태에 빠지게 될 수 있는 것 입니다. 이와 같이 한 row 를 집중 access 하는 경우 dead lock 상황을 고려 해야 합니다.

예) 범하기 쉬운 오류

현재의 TABLE_A 의 AMT 가 100 이라고 가정하자. 다음과 같이 hold lock 을 사용하여 복수 Tran 이 발생 한다고 가정할 때,Tran A 의 update 결과 값(200)을 반영하여 Tran B 가 300 이 되기를 기대 한다면 잘못된 경우입니다

Tran A

Begin tran;

Select Amt from Table_A Holdlock

where a = H_a; <= 100

New_Amt = Amt + 100;

Update Table_A

set Amt = New_Amt <=200

where a= H_a;

Tran B

Begin tran;

Select Amt from Table_A Holdlock

where a = H_a; <=100

New_Amt = Amt + 100;

Update Table_A

set Amt = New_Amt <=200

where a= H_a;

Tran B 에서 먼저 선행된 Tran A 의 결과값을 반영하기 위해서 hold lock 을 걸었다면, 명백한 오류입니다.

Adaptive Server Enterprise15.0 Page: 18 Version: 0.1, 22 Aug 2006

Page 27: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

Hold lock 은 shared lock 을 허용하므로, Tran A 의 update 문장 전까지는 100 을 select 합니다

예) 해결 방법 1

transaction 을 시작하면서 dummy update 를 수행하여, exclusive lock 을 강제로 잡습니다.

Tran A

Begin tran;

Update Table_A

set Amt = Amt <= dummy update where a= H_a;

Select Amt from Table_A

where a = H_a; <= 100

New_Amt = Amt + 100;

Update Table_A

set Amt = New_Amt <=200

where a= H_a;

Tran B

Begin tran;

Update Table_A

set Amt = Amt <= dummy update where a= H_a;

Select Amt from Table_A

where a = H_a; <=200

New_Amt = Amt + 100;

Update Table_A

set Amt = New_Amt <=300

wherea=H_a;

Tran B 는 먼저 수행된 TRAN A 가 Commit 될 때까지 기다렸다가, 반영된 값을 select 합니다. 이 경우 Transaction 을 최소화 하는 것을 생각해야 합니다.

예) 해결 방법 2

update 시에 연산하여, 항상 최신의 값에 update 합니다.

Tran A

Begin tran;

Select Amt from Table_A

where a = H_a; <= 100

Update Table_A

set Amt = Amt +100 <=200

where a= H_a;

Tran A

Begin tran;

Select Amt from Table_A

where a = H_a; <= 200

Update Table_A

set Amt = Amt +100 <=300

where a= H_a;

Adaptive Server Enterprise15.0 Page: 2 Version: 0.1, 22 Aug 2006

Page 28: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

위 방법은 실제 (방법 1)에 비해 Lock duration 을 최소화하므로, 권장하는 방안입니다. select 한 값은 타 transaction 에 공유(shared)될 수 있음을 주의하여 사용 해야 합니다. (방안 1)과 (방안 2)를 선택함은 업무특성에 따라 개발자가 결정 해야 합니다. 이를 위해서는 lock 의 mechanism 과 타 transaction 의 관계를 분명히 이해 해야 합니다.

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

isolation level 0

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

예)

SET TRANSACTION ISOLATION LEVEL 0

or

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

SELECT Passwd,DeptBrSect INTO :Br_Passwd, :Br_DeptBrSect

FROM COCOMM..COM_DEPT_BR_INFO (index COM_BR_INFO_PK)

WHERE DeptBrCd = :INH_BrCd

AT ISOLATION READ UNCOMMITTED;

or

AT ISOLATION 0;

isolation level 1

isql 에서 기본(default) mode 로 사용되며 select 시 읽혀지는 rows 에 대해 순간적으로 Shared Lock 이 걸리며 읽힌 후 바로 Lock 이 해제됩니다

Adaptive Server Enterprise15.0 Page: 2 Version: 0.1, 22 Aug 2006

Page 29: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

select 문장에서 Hold lock option 을 주게 되면 rows 를 읽을 때 잡히는 Shared Lock 은 바로 해제가 되지 않으며 commit/rollback 명령에 의해서만 해제 됩니다

isolation level 2

같은 transaction 에 서 동일한 질의에 대해 동일한 결과 값을 보장해주기 위한 노력으로 select 시 발생한 Shared Lock 은 transaction 이 종료(commit or rollback)될 때까지 해제되지 않는다

Data rows lock scheme 에서만 지원되며 같은 transaction 에서 동일한 질의에 대해 Phantom 현상을 허용합니다.

isolation level 3

실행되는 모든 select 문에 대해 Hold lock option 을 준 효과를 발휘하다. 따라서 Commit/Rollback 전 까지는 read 된 모든 rows 에 대해서 Shared Lock 이 해제 되지 않으므로 유의 하여야 합니다

5.6 Lock 탐지방법 sp_who

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

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 가 blocked 되고 있다

sp_lock

Adaptive Server Enterprise15.0 Page: 3 Version: 0.1, 22 Aug 2006

Page 30: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

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

5.7 Lock wait LOCK wait time 한계를 설정할 수 있습니다. 그러나 프로그램에서는 인위적인 lock wait 사용은 자제해 주시기 바랍니다

server-wide setting

sp_configure "lock wait period" [, no_of_seconds]

기본 설정 값은 lock 이 해제 될 때까지 기다리는 것 입니다.

table 단위로 setting

lock table table_name in {share | exclusive} mode [wait [no_of_seconds] | nowait]

해당 테이블을 인위적으로 blocking 하고자 할 경우 사용합니다.

connection 에 setting

set lock { wait no_of_seconds | nowait }

수행중인 transaction 이 lock wait 상태에서 timeout 을 만나면 다음 message 를 볼 수 있습니다

Adaptive Server Enterprise15.0 Page: 4 Version: 0.1, 22 Aug 2006

Page 31: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

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 됩니다

5.8 Table Lock Scheme 데이터가 저장되는 각 테이블은 업무의 성격, transaction 성격에 따라서 각각 다른 형태의 lock scheme 을 적용할 수 있으며 특징은 다음 표와 같습니다

Allpages Datapages Datarows Index 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작업을 해야 합니다

Adaptive Server Enterprise15.0 Page: 5 Version: 0.1, 22 Aug 2006

Page 32: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

6. Deadlock

2 개 또는 그 이상의 User Process 가 동시에 같은 데이터를 접근하려 할 때 transaction 이 교차되면서 더 이상 진행되지 않는 상태를 말합니다.

6.1 ASE 에서 deadlock 처리 Dead Lock 이 발생 하면 Lock Manager 가 교착상태의 task 들에 대한 CPU Time 을 계산하여 Time 이 적은 process 를 kill(abort)시킵니다

6.2 Deadlock 방지법 모든 transaction 에서 같은 순서로 table 을 access 하게 합니다

가능한 transaction 을 작게 합니다

transaction 안에서 user 의 input 을 기다리는 것을 피합니다

deadlock 이 발생하면 error #1205 를 받으므로 다시 Transaction 을 실행 하든 아니면 error 내용을 user 에게 통보하고 끝내든지 합니다.

6.3 Deallock 탐지 Dead Lock 추적 정보는 DBCC trace flag,1204 와 3605 를 on 하여 생성

합니다

1204 : ASE 에게 deadlock 이 발생하면 deadlock 추적, 정보를 생성하도록 지시합니다

3605 : ASE 에게 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 00:00000:00001:2000/12/01 09:54:14.06 server Deadlock Id 1 detected

Deadlock 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.

Adaptive Server Enterprise15.0 Page: 6 Version: 0.1, 22 Aug 2006

Page 33: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

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' lock on 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' lock on row 0 page 1101 of the 'A' table in database 5 but process (Familyid 1, Spid 1) 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를 설정하는 것은 ASE의 performance를 크게 떨어 드릴 수가 있습니다. 해당 trace flag는 debug를 할 경우에만 사용 하는 것이 좋습니다

Adaptive Server Enterprise15.0 Page: 7 Version: 0.1, 22 Aug 2006

Page 34: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

7. Data Type

7.1 ASE Data type Numeric : numeric,bigint, int, smallint,tinyint, real, money, decimal….

Character : char, varchar

Date/time : date, time

LOBs : text, image

ASE 는 위와 같이 크게 4 가지 종류의 데이터 타입을 가지고 있습니다.

7.2 데이터 타입 선언

7.2.1 테이블의 열에 대한 데이터 유형 선언

다음 구문을 사용하여 create table 또는 alter table 구문에서 새 열의 데이터 유형을 선언합니다.

create table [[database.]owner.]table_name

(column_name datatype [identity | not null | null]

[, column_name datatype [identity | not null |

null]]...)

alter table [[database.]owner.]table_name

add column_name datatype [identity | null

[, column_name datatype [identity | null]...

예)

create table sales_daily

(stor_id char(4)not null,

ord_num numeric(10,0)identity,

ord_amt money null)

7.2.2 배치 및 프로시저 에서 로컬 변수 선언

다음 구문을 사용하여 배치나 내장 프로시저에 있는 로컬 변수에 대한 데이터 유형을 선언합니다.

Adaptive Server Enterprise15.0 Page: 8 Version: 0.1, 22 Aug 2006

Page 35: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

예)

declare @variable_name datatype [, @variable_name datatype ]...

7.2.3 Stored Procedure 에서 매개 변수 형 선언

Stored Procedure 매개 변수의 형 선언은 다음과 같이 합니다.

예)

create procedure auname_sp @auname varchar(40)

select au_lname, title, au_ord

from authors, titles, titleauthor

where @auname = au_lname

and authors.au_id = titleauthor.au_id

and titles.title_id = titleauthor.title_id

7.3 데이터 타입 변환 하나의 데이터 유형에서 다른 데이터 유형으로의 변환 중 대부분은 Adaptive Server Enterprise 가 자동으로 처리하는데 이를 묵시적 변환이라고 합니다. 그 외 변환은 convert, hextoint 및 inttohex 함수를 사용하여 명시적으로 수행해야 합니다.

예)

> select hextoint('a53a8a')

2> go

-----------

10828426

1> select convert(char(20),getdate())

2> go

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

Sep 7 2006 5:12PM

Adaptive Server Enterprise15.0 Page: 9 Version: 0.1, 22 Aug 2006

Page 36: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

7.4 공백처리 이번에는 문자 데이터의 고정길이와 가변길이 데이터의 공백처리에 대해서 언급 하도록 하겠습니다. SYBASE ASE 에서는 기본적으로 NULL, Not NULL 을 정의하지 않으면 Not NULL attribute 값을 가지게 되어 있습니다. 다들 알고 있는 내용이겠으나 주의 깊게 다시 한번 확인 하시기 바랍니다

예)

create table spaces (cnot char(5) not null,

cnull char(5) null,

vnot varchar(5) not null,

vnull varchar(5) null,

explanation varchar(25) not null)

insert spaces values ("a", "b", "c", "d", "pads char-not-null only")

insert spaces values ("1 ", "2 ", "3 ","4 ", "truncates trailing blanks")

insert spaces values (" e", " f", " g"," h", "leading blanks, no change")

insert spaces values (" w ", " x ", " y "," z ", "truncates trailing blanks")

insert spaces values ("", "", "", "","empty string equals space" )

select "[" + cnot + "]","[" + cnull + "]","[" + vnot + "]","[" + vnull + "]",

explanation from spaces

[결과 셋]

explanation

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

[a ] [b] [c] [d] pads char-not-null only

[1 ] [2] [3] [4] truncates trailing blanks

[ e] [ f] [ g] [ h] leading blanks, no change

[ w ] [ x] [ y] [ z] truncates trailing blanks

[ ] [ ] [ ] [ ] empty string equals space

이 예제는 열의 데이터 유형과 null 유형이 공백을 처리하는 방법을 결정하기 위해 어떻게 상호 작용하는지 보여 줍니다.

Adaptive Server Enterprise15.0 Page: 10 Version: 0.1, 22 Aug 2006

Page 37: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

char not null 및 nchar not null 열만 열의 전체 너비에 채워지고 char null 열은 varchar 처럼 취급되며 nchar null 열은 nvarchar 처럼 취급됩니다.

unichar not null 열만 열의 전체 너비에 채워지고 unichar null 열은 univarchar 처럼 취급됩니다.

선행 공백은 영향을 받지 않습니다

char, unichar 및 nchar not null 열 이외의 후미 공백은 잘립니다

7.5 NULL 사용

7.5.1 기본 지침

업무 성격상 데이터 값이 입력되는 빈도가 적은 칼럼은 null 을 적용

데이터 값이 가변적이고 값의 입력 여부가 불명확 하거나 할 경우는 반드시 NULL 허용이 적용되어야 하지만 그렇지 않을 경우, 즉 일반적으로 정상적인 값이 들어갈 경우, 반드시 not null 을 사용합니다.

index 는 varchar 또는 null 허용 을 하지 맙시다

index 를 search 하는 시간의 차이가 발생하므로 일반 칼럼만 적용하도록 합니다

char 칼럼의 경우 space 또는 실제 length 보다 적은 length 의 값이 들어갈 확률이 많을 경우, varchar 값을 사용합니다.

ASE 의 default 는 not null 입니다.

7.5.2 Null 허용 칼럼의 정의

500 MB 이상의 중대형 테이블들의 numeric 칼럼 중 0 값이 존재할 확률이 많을 경우에 한하여 null 허용을 검토 합니다. 칼럼 추가의 경우는 null 허용을 원칙으로 합니다

Adaptive Server Enterprise15.0 Page: 11 Version: 0.1, 22 Aug 2006

Page 38: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

null, varchar 로 인한 space 절감 효과가 있는지 고려하여 적용

numeric(4) , char(3) 이하는 즉 4 byte 길이 이하는 null, varchar 적용을 하지 않는 것을 권고 합니다. 그러나 항시 프로그램에서 NULL 칼럼 값 return 을 대비한 코딩이 뒤 따라야 합니다

7.5.3 Null 사용 시 프로그래밍

UPDATE 시 반드시 isnull 처리합니다.

예)

UPDATE RDZ_ENTRUS_TRD set TrdPValAmt = isnull(TrdPValAmt,0) + @AddValue where…..

UPDATE RDZ_ENTRUS_TRD set TrdPValAmt = isnull(sum(TrdPValAmt),0) where …..

INSERT 시

예)

declare

@a1 numeric(5),

@b1 numeric(5),

@c1 numeric(5),

@d1 numeric(5),

@e1 numeric(5)

begin

select @a=0,@b=1,@c=0,@d=5

/* Null 변경 전: insert TEMP_A values (@a,@b,@c,@d) */

/* Null 변경 후 */

insert TEMP_A values (

case when @a = 0 then null else @a end

, case when @b = 0 then null else @b end

, case when @c = 0 then null else @c end

Adaptive Server Enterprise15.0 Page: 12 Version: 0.1, 22 Aug 2006

Page 39: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

, case when @d = 0 then null else @d end)

end

SELECT /SUM /MAX /MIN

예)

select UserId, Amt ,Qty from SALARY ....

=> select UserId, isnul(Amt,0),isnull(Qty,0) from SALARY...

7.6 기타 지침 특히 숫자 데이터의 경우 Numeric 보다는 bigint, int, smallint 등 사용을

권장 합니다. 4 자리 이하 수의 경우 smallint 를, 9 자리 이하 수는 int 등의 사용을 고려합시다. 그리고 필요 이상의 데이터 길이 선언은 저장공간의 낭비뿐 아니라 어플리케이션 성능에 좋지 않으므로 적정의 데이터 길이 선언은 운영과 성능을 위해서 반드시 검토되어야 할 사항 입니다

인덱스 칼럼 들은 반드시 고정길이 데이터 형식을 사용해야 합니다.

7.7 데이터 Type 비교

Oracle Sybase Comments

VARCHAR2(n) VARCHAR(n)

NVARCHAR2(n) NVARCHAR(n)

CHAR CHAR

CHAR(1) BIT true/false and yes/no types of

data can be stored.

Storage size is 1 byte, can hold

either 0 or 1

CHAR(n) CHAR(n)

NCHAR(n) NCHAR(n)

NUMBER(3) TINYINT Sybase tinyint ranges from 0-

255

NUMBER(4) SMALLINT Sybase smallint ranges from –32768 to +32767

Adaptive Server Enterprise15.0 Page: 13 Version: 0.1, 22 Aug 2006

Page 40: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

NUMBER(9) INT Range of integer is 231 -1

(2,147,483,647) to -231

(-2,147,483,648)

NUMBER(19,4) MONEY money and smallmoney

datatypes stores monetary

data. It stores to 4 digits of

precision to the right of

the decimal point, and to

approx +/-$214k for

smallmoney, approx +/-$922T

for money to the left of

the decimal.

NUMBER(19,4) SMALLMONEY See above comments for

Sybase money.

REAL,

FLOAT,

NUMBER

DOUBLE

FLOAT, FLOAT

REAL

FLOAT(p) DOUBLE

PRECISION

FLOAT(p) FLOAT(p)

NUMBER(p,s) NUMERIC(p,s) The number(p,s) datatype of

oracle map exactly to

numeric and decimal types of

Adaptive Server

NUMBER(p,s) DECIMAL(p,s) See above comments Oracle

number

BINARY_FLOAT -

BINARY_DOUBLE -

DATE DATETIME datetime values are accurate to

1/300 second on

platforms that support this level

of granularity, holds

dates between January 1, 1753

and December 31, 9999

TIMESTAMP DATETIME

DATE DATE holds dates from January 1,

0001 to December 31,

9999. Storage size is 4 bytes

Adaptive Server Enterprise15.0 Page: 14 Version: 0.1, 22 Aug 2006

Page 41: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

DATE SMALLDATETIME holds dates from January 1,

1900 to June 6, 2079, with

accuracy to the minute. Its

storage size is 4 bytes

TIME time is between 00:00:00:000

and 23:59:59:999

TIMESTAMP DATETIME datetime value is accurate to

1/300 second

CLOB Text text are variable-length

columns that can hold up to

2,147,483,647 (231 - 1) bytes

of printable characters.

BLOB Image image are variable-length

columns that can hold up to

2,147,483,647 (231 - 1) bytes

of bytes of raw binary data.

LONG TEXT text are variable-length

columns that can hold up to

2,147,483,647 (231 - 1) bytes

of printable characters.

RAW(n) BINARY(n)

RAW(n) VARBINARY(n)

RAW(n) IMAGE

BFILE Not supported

Adaptive Server Enterprise15.0 Page: 15 Version: 0.1, 22 Aug 2006

Page 42: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

8. 테이블 과 데이터 접근

8.1 오브젝트 비교 RDBMS 에서 통상적으로 사용하고 있는 객체들에 대한 용어를 비교해 보았습니다.

Oracle Sybase

Constraints Constraints

Database Links Component Integration Service

Functions Function, Stored procedure

Index Index

Index-organized table Clustered index

Package Stored procedure

Procedure Stored procedure

Sequence Identity

Synonym Basic naming rule of objects to access an object in a DB

Table Table

Triggers Triggers

View View

8.2 테이블 목록 확인 Interactive SQL 혹은 isql 에서 테이블 목록 확인

예)

1>sp_help [테이블명]

2>go

SQL 을 이용한 확인

1>select name from sysobjects where type = “U”

2>go

U: table, P: stored procedure, V:view, T:trigger

Adaptive Server Enterprise15.0 Page: 16 Version: 0.1, 22 Aug 2006

Page 43: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

Sybase central 에서 확인

Central 로 접속 후 > database 선택> 해당 데이터베이스 선택>테이블 목록

8.3 테이블 접근 SQL 에서 테이블 기술

예) 데이테베이스명.dbo.테이블명 혹은 데이터베이스명..테이블명

SELECT DepoTotAmt, SecuSubstAmt, ghtSubstAmt,

~

FROM CXMASTER..CUA_ENTRUS_ACCT

~

8.4 Computed column 수식, 함수, 수 연산자, 경로명 등으로 칼럼을 생성 할 수 있는 기능으로 Computed 칼럼을 미리 검증 받아 데이터 테이블에 저장할 수도 있고 (materialized computed 칼럼), 접근 시마다 검증 받을 수도 있으며(virtual computed 칼럼) 복잡한 데이터 타입을 사용해야 할 때(데이터 타입의 결합 및 분해) 유용 합니다

Computed 칼럼 인덱스

인덱스 생성 시 하나 이상의 computed 칼럼을 인덱스 키로 사용 가능하며 XML, Java 클래스, text, Image 와 같은 복잡한 데이터에 대한 인덱스 생성이 가능 합니다

예) create table rental

(cust_id int,

start_date as getdate() materialized,

today as getdate(),

prod_id int)

입력이나 수정 시 값이 결정되어

저장됨

Select할 때 값이 결정되어 display됨

8.4.1 유리한 점

어플리케이션 개발과 유지 향상

Adaptive Server Enterprise15.0 Page: 17 Version: 0.1, 22 Aug 2006

Page 44: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

DML 성능 향상

XML, Java 클래스, objects, text, Image 와 같은 복잡한 데이터에 대한 비교, order by, group by, DSS 성능 향상

8.4.2 데이터 materialization 옵션

Materialized vs. Non-materialized : Virtual 여부와 같은 의미로 그 칼럼의 결과 값이 이미 저장이 되어 있는지 아니면 실행할 당시 생성이 되는지 여부에 따라 결정 됩니다. 본 프로젝트에서 computed column 을 사용하고자 한다면 materialized computed column 을 사용할 것을 권장합니다

Not materialized (virtual)

① 입력/수정 시 계산되지 않습니다

② query 가 수행될 때 계산됩니다

③ 가상 칼럼은 저장공간을 사용하지 않습니다

④ 기본 설정은 not materialized 입니다

예)

1> create table tab1 (

2> part_no int not null,

3> price decimal(6,2) not null,

4> orders int not null,

5> total_sales as round((price * orders),2) not materialized

6> )

7> go

1> insert into tab1 values (123,19.99,10)

2> insert into tab1 values (456,15.99,20)

3> insert into tab1 values (789,19.99,3)

4> go

1> select * from tab1

2> go

part_no price orders total_sales

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

Adaptive Server Enterprise15.0 Page: 18 Version: 0.1, 22 Aug 2006

Page 45: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

123 19.99 10 199.90

456 15.99 20 319.80

789 19.99 3 59.97

(3 rows affected)

1> update tab1 set orders = orders + 10

2> go

(3 rows affected)

1> select * from tab1

2> go

part_no price orders total_sales

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

123 19.99 20 399.80

456 15.99 30 479.70

789 19.99 13 259.87

(3 rows affected)

****not materialized 방법 중에는 다음과 같은 두 가지 개념이 있습니다

① Deterministic

주어진 입력 값에 따라 항상 같은 return 값을 가지는 것을 의미합니다

1>create table my_sum (a int, b int, c as a+b)

2>go

“c” 는 주어진 a, b 값에 의해 항상 일정한 값은 return 합니다

② Non Deterministic

주어진 입력 값에 따라 항상 다른 return 값을 가지는 것을 의미합니다

1>Create table inventory (part_id int, stock_date datetime,

2>age as datediff(dd,stock_date,getdate()))

3>go

“age” 는 매일 다른 값을 가지게 됩니다

Materialized

Adaptive Server Enterprise15.0 Page: 19 Version: 0.1, 22 Aug 2006

Page 46: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

① 입력/ 수정 시 값이 결정됩니다

② query 가 수행될 때 다시 계산되지 않습니다

③ 테이블에 직접 저장됩니다

④ 인덱스는 반드시 materialized 칼럼만 가능 합니다

예)

1> create table upper_authors (

2> fname varchar(25) not NULL,

3> lname varchar(25) not NULL,

4> upper_lname as upper(lname) materialized

5> )

6> go

1> insert into upper_authors values ('John','Smith')

2> go

(1 row affected)

1> select * from upper_authors

2> go

fname lname upper_lname

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

John Smith SMITH

(1 row affected)

8.5 Function based index 인덱스 생성 시 하나 이상의 수식 또는 함수를 인덱스 키로 사용 가능한 기능으로 Computed 칼럼 과 는 다르게 데이터가 항상 미리 검증되어 인덱스 페이지에 저장되기 때문에 접근 할 때마다 검증 받을 필요가 없습니다.

예)

1>CREATE INDEX product_total ON orders (unit*price*1.1)

2>go

1>SELECT unit*price*1.1 FROM orders WHERE unit*price*1.1 > 2002

2>go

Adaptive Server Enterprise15.0 Page: 20 Version: 0.1, 22 Aug 2006

Page 47: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

ROOT:EMIT Operator |SCAN Operator

| FROM TABLE

| orders

| Index : product_total => function based index 사용

| Forward Scan.

| Positioning by key.

| Index contains all needed columns. Base table will not be read.

| Keys are:

| sybfi2_1 ASC

| Using I/O Size 4 Kbytes for index leaf pages.

| With LRU Buffer Replacement Strategy for index leaf pages.

8.6 Derived Table(in-line view) 1 개 이상의 테이블에서 어떤 Query 를 사용하여 직, 간접적으로 유도된 테이블을 말합니다. 즉 base table 이 없이 Query 에 의해서 만들어진 결과 셋으로 from 절에 기술된 expression 으로 유도됩니다.

8.6.1 특징

SQL derived table 은 table 이름과 선택적인 column list 로 구성됩니다.

Base tables 로 부 터 Query 를 수행하여 생성됩니다.

View 가 사용되어 지는 곳이면 어디에서나 사용 가능합니다.

#temp table 과는 다르게 해당 Query 를 위해서만 존재합니다.

SQL derived tables 사이의 join 및 tables/views 와의 join 도 허용합니다.

8.6.2 장점

#temp table 의 사용 시 create/drop 의 반복적인 요구로 system catalog tables 에 lock contention 이 발생 할 수 있는데 이러한 걱정을 할 필요가 없습니다.

#temp table 을 사용할 경우 하나 이상의 SQL 문을 사용하여 여러 개의 #temp tables 을 생성하여 처리해야 하는 것을 SQL derived table 을 사용할 경우에는 하나의 SQL 문에서 결과를 가져올 수 있습니다.

Adaptive Server Enterprise15.0 Page: 21 Version: 0.1, 22 Aug 2006

Page 48: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

8.6.3 사용 예

SELECT, SELECT INTO, INSERT 및 CREATE VIEW statements

예)

1>select pub_date into pub_dates

2>from (select pubdate from titles) dt_e

3>where pubdate = "450128 12:30:1PM"

4>go

1>create view psych_titles as

2>select * from (select * from titles where type = "psychology") dt_psych

1>insert into colo_authors

2>select * from (select * from authors where state = "CO") dt_co

3>go

1>select dt_b.book_title, dt_b.tot_sales

2>from (select title, total_sales from titles) dt_b (book_title, tot_sales)

3>where dt_b.book_title like "%Computer%"

4>go

SUBQUERY 의 FROM 절에서도 사용 가능

예)

1>select pub_name from publishers

2>where "business" in (select type from (select type from titles, publishers

where titles.pub_id = publishers.pub_id) dt_titles)

3>go

8.6.4 구현 시 주의사항

nesting level 은 최대 25 개 까지 가능 합니다

예)

1>select postalcode

from (select postalcode

from (select postalcode

from authors) dt_1) dt_2

2>go

Adaptive Server Enterprise15.0 Page: 22 Version: 0.1, 22 Aug 2006

Page 49: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

update, delete 문에서 사용 불가능 합니다

parallel, index 및 prefetch option 을 명시할 수 없습니다

Correlated SQL derived tables 은 ANSI 표준이 아니며 ASE 는 지원하지 않습니다

예)

1>select * from

2>(select * from titles where titles.pub_id =

3> dt_publishers2.pub_id) dt_publishers1,

4>(select * from publishers where city = "Boston") dt_publishers2

5>where dt_publishers1.pub_id = dt_publishers2.pub_id

6>go

즉 위 예에서 dt_publishers1 derived table 내부에서 dt_publishers2 를 참조할 수 없습니다.

제약사항에 위반되는 SQL derived tables 의 경우 Error#107 이 발생함

예)

(x)

1>select d1.* from (select * from publishers where pub_id = d2.pub_id) d1,

2> (select * from titles where pub_id = "1699") d2

3>where d1.pub_id = d2.pub_id

4>go

위의 예에서 d1 의 조건 절에서 d2 를 참조할 수 없음.

(o)

1>select * from publishers, (select * from titles where pub_id = "1699") d2

2>where publishers.pub_id = d2.pub_id

3>go

SQL derived table 의 바깥쪽에서 correlated references 를 허용하지 않음

Adaptive Server Enterprise15.0 Page: 23 Version: 0.1, 22 Aug 2006

Page 50: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

예)

(x)

1>select * from publishers

2>where pub_id in (select pub_id from

3> (select pub_id from titles

4> where pub_id = publishers.pub_id) dt_publishers)

6>go

만약 SQL derived tables 에서 column list 를 명시하지 않는다면 derive table expression 에서 target list 에서는 column names 이 동일해야 합니다.

1>select dt_b.title, dt_b.total_sales from (select title, total_sales from titles) dt_b

2>where title = "BU1032“

3>go

derive table expression 에서 column name 이 없을 경우 target list 에서 사용할 수 없습니다.

(x)

1>select * from (select count(ord_num) from sales) dt

2>go

(o)

1>select * from (select count(ord_num) cnt from sales) dt

2>go

1>select * from (select count(ord_num) from sales) dt(cnt)

2>go

Adaptive Server Enterprise15.0 Page: 24 Version: 0.1, 22 Aug 2006

Page 51: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

9. Partition

대용량 테이블을 partitioning 한다는 것은 하나의 테이블을 여러 개의 세그먼트로 나눈다는 의미입니다. 즉 하나의 테이블이나 인덱스가 동일한 논리적 속성을 가진 여러 개의 단위(partition)로 나누어져 저장하는 되는 것을 뜻합니다. 특히 관리해야 할 데이터가 늘어나면 성능과 운영의 관점에서 여러 가지 부작용을 만들 수 있는데 이를 해결할 수 있는 효율적인 방법 가운데 하나가 partitioning 입니다. partitioning 은 보통 다음과 같은 장점을 갖고 있습니다.

데이터 접근 시 범위를 줄여 성능을 향상 시킵니다.

물리적으로 여러 영역으로 partitioning 해 전체 데이터의 훼손 가능성이 줄어들고 데이터 가용성이 향상됩니다.

각 partition 별로 유지보수 작업을 할 수 있습니다. (dbcc, reorg, index , bcp..etc)

테이블의 partition 단위로 디스크 I/O 를 분산해 부하를 줄일 수 있습니다.

9.1 Partition 의 종류 Range

Hash

List

Round Robin

9.2 Range partition range partitioning 은 어떤 특정 칼럼의 정렬 값을 기준으로 분할하는 것입니다. 주로 순차적인(historical) 데이터를 관리하는 테이블에 많이 사용됩니다. 예를 들어 몇 년 동안의 데이터를 테이블에 유지해야 하지만 실제로는 최근 수개월 혹은 수년의 데이터 접근이 일반적이라면 range partition 을 고려해 볼 필요가 있습니다. 위의 경우 이를 년도 별, 월 별로 partitioning 하여 관리한다면 전체 데이터베이스의 성능을 향상시킬 수 있습니다

Adaptive Server Enterprise15.0 Page: 25 Version: 0.1, 22 Aug 2006

Page 52: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

9.2.1 언제 사용하는가

특정키 값을 기준으로 순차적으로 나열 할 수 있는 대량의 데이터를 저장 할 테이블

수 개월 혹은 수 년간의 history 데이터를 저장할 테이블

시계 열 분석이 필요한 데이터를 저장 할 테이블

9.2.2 구현 예

segment seg1, seg2, seg3 을 만들고, TABLE 명 customer 를 만드는데, Range partition 을 cust_ptn1, cust_ptn2, cust_ptn3 라 부르고 각각은 customer key 값이 20000 보다 작거나 같으면 cust_ptn1 에, 40000 보다 작거나 같으면 cust_ptn2 에 그리고 60000 보다 작거나 같으면 cust_ptn2 에 저장되는 테이블을 보여주고 있습니다.

cust_ptn3: values <=60000

Segment 3

cust_ptn2: values <=40000

Segment 2

cust_ptn1:values <=20000

Segment 1

cust_ptn3: values <=60000

Segment 3

cust_ptn3: values <=60000

Segment 3

cust_ptn2: values <=40000

Segment 2

cust_ptn2: values <=40000

Segment 2

cust_ptn1:values <=20000

Segment 1

cust_ptn1:values <=20000

Segment 1

① Device 생성

1> disk init

2> name='dev1',physname='/dev/vg1/rvg1_seg1,size='500M'

1> disk init

2> name='dev2',physname='/dev/vg1/rvg1_seg2,size='500M'

1> disk init

2> name='dev3',physname='/dev/vg1/rvg1_seg3,size='500M'

② Database alter

1> alter database pubs2 on dev1 = 500

2> alter database pubs2 on dev2 = 500

3> alter database pubs2 on dev3 = 500

Adaptive Server Enterprise15.0 Page: 26 Version: 0.1, 22 Aug 2006

Page 53: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

③ Segment 추가

1> exec sp_addsegment seg1, pubs2, dev1

2> exec sp_addsegment seg2, pubs2, dev2

3> exec sp_addsegment seg3, pubs2, dev3

④ Table 생성

Create table customer ( c_custkey integer not null

, c_name varchar(20) not null

, c_address varchar(40) not null

, other columns)

partition by range (c_custkey)

(cust_ptn1 values <= (20000) on seg1,

cust_ptn2 values <= (40000) on seg2,

cust_ptn3 values <= (60000) on seg3 )

9.3 Hash Partition 해시 partitioning 은 특정 칼럼 값에 해시 함수를 적용해 분할하는 방식으로, 데이터의 관리 보다는 성능 향상에 초점을 맞춘 partition 기법 입니다. 레인지 partitioning 은 각 범위에 따라 데이터 양이 달라 분포도가 일정치 않은 단점이 있는데, 해시 partitioning 은 이런 단점을 보완해 일정한 분포를 가진 partition 으로 나누고, 균등한 분포도를 가질 수 있도록 합니다. 실제로 분포도를 정의하기 어려운 테이블을 partition 할 때 많이 이용하고 2 의 배수 개수로 partitioning 하는 것이 일반적입니다. range partition 과는 달리 각 partition 에 지정된 값들을 DBMS 가 결정하므로 각 partition 에 어떤 값들이 들어 있는지 알 수 없습니다.

9.3.1 언제 사용하는가

빠른 성능이 필요로 하는 테이블

응용프로그램에서 자주 ordering 또는 grouping 되는 칼럼이 특별한 순차가 정해져 있지 않은 큰 테이블

각 파티션 별로 데이터를 고르게 분산

파티션 구분을 위한 키 구분이 필요 없습니다

데이터 일그러짐이 발생하지 않는 키 값을 가진 데이터

Adaptive Server Enterprise15.0 Page: 27 Version: 0.1, 22 Aug 2006

Page 54: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

9.3.2 구현 예

Create table lineitem ( l_orderkey integer not null

, l_partkey integer not null

, l_suppkey integer not null

, l_linenumber integer not null

, l_quantity double not null

, l_extendedprice double not null

, other columns)

partition by hash (l_orderkey, l_linenumber)

(litem_hash1 on segment1,

litem_hash2 on segment2,

litem_hash3 on segment3,

litem_hash4 on segment4 )

litem_hash2:

Segment 2

litem_hash1:

Segment 1

litem_hash3:

Segment 3

litem_hash4:

Segment 4

litem_hash2:

Segment 2

litem_hash2:

Segment 2

litem_hash1:

Segment 1

litem_hash1:

Segment 1

litem_hash3:

Segment 3

litem_hash3:

Segment 3

litem_hash4:

Segment 4

litem_hash4:

Segment 4

9.4 List Partition 리스트 partition 은 특정 칼럼의 특정 값을 기준으로 partition 을 하는 방식입니다. 각 Partition 에 적어도 한 값이 적용되면서, 각 값은 한 Partition 에 속해야 합니다. 만약 insert 시 그 값이 어느 Partition 에도 속하지 않는다면, Insert 되지 않습니다. 한 Partition 에서 값들의 순서는 없습니다.

9.4.1 언제 사용하는가

주로 이질적인(distinct) 값이 많지 않고 분포도가 비슷하며

Adaptive Server Enterprise15.0 Page: 28 Version: 0.1, 22 Aug 2006

Page 55: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

다양한 SQL 에서 해당 칼럼의 조건이 많이 들어오는 경우 유용하게 사용됩니다.

중복이 많은 일정 KEY 값을 갖는 경우 유용합니다

9.4.2 구현 예

Create table nation ( n_nationkey integer not null

, n_name char(25) not null

, n_regionkey varchar(30) not null

, n_comment varchar(152) not null )

partition by list (n_regionkey)

( region1 values (‘Americas’) on segment1,

region2 values (‘Asia’) on segment2,

region3 values (‘Europe’) on segment3,

region4 values (‘Australia’, ‘Other’) on segment4)

Segment 1

region2:region1: region3: region4:

Segment 1 Segment 1 Segment 1Segment 1

region2:region1: region3: region4:region2:region1: region3: region4:region2:region2:region1:region1: region3:region3: region4:region4:

Segment 1 Segment 1 Segment 1

9.5 Round Robin Round Robin Partition 은 partition 과 관련 어떤 정의나 키가 존재하지 않으며 ASE engine 이 일정한 규칙에 의해서 자동으로 각 partition 에 데이터를 일정하게 분배하는 방식의 partition 을 이야기 합니다.

9.5.1 언제 사용하는가

Round Robin Partition 역시 hash partition 과 마찬가지로 DB 성능을 위한 것이라고 이해하면 됩니다.

Insert 가 많은 테이블( hot-spot 방지를 위해서 )

Adaptive Server Enterprise15.0 Page: 29 Version: 0.1, 22 Aug 2006

Page 56: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

9.5.2 구현 예

part1:

Segment1

part2:

Segment2

part3

Segment3

part1:

Segment1

part1:

Segment1

part2:

Segment2

part2:

Segment2

part3

Segment3

part3

Segment3

Create table office_table( office_id char(3) not null,

office_name varchar(30) not null,

address varchar(40) not null,

office_mgr int not null)

partition by roundrobin

(part1 on segment1,

part2 on segment2,

part3 on segment3)

9.6 Partition Index

9.6.1 Global Index

테이블의 모든 Partition 에 걸쳐있으며

Range, Hash 또는 List 방식으로 Partition 된 테이블의 non clustered index 입니다

Round Robin 방식의 Partition 된 Table 인 경우는 clustered 또는 non clustered 가 있을 수 있습니다

Adaptive Server Enterprise15.0 Page: 30 Version: 0.1, 22 Aug 2006

Page 57: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

create unique index ci_nkey_ckey on customer(c_nationkey, c_custkey) on part4

9.6.2 Clustered Local Index

데이터 파티션 별( range, hash, list, round robin )로 clustered index 가 생성 가능합니다

create unique clustered index ci_nkey_ckey on customer(c_custkey, c_nationkey)

9.6.3 Non Clustered Local Index

데이터 파티션 별( range, hash, list, round robin )로 Non clustered index 가 생성 가능합니다

Create unique index ci_nkey_ckey on customer(c_nationkey, c_custkey) on segment4 local index

Adaptive Server Enterprise15.0 Page: 31 Version: 0.1, 22 Aug 2006

Page 58: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

9.7 partition key rule range 와 hash partition 에서 composite key 를 사용할 수 있습니다

다음과 같은 데이터 타입은 partition key 로 인정하지 않습니다

Text / Image, Bit, Java Class, Computed Columns

Key type and partition bound type must be compatible

Key column 은 반드시 고정 길이 타입을 사용할 것을 권고 합니다.

9.8 Partitioning 효과 query 처리향상

- Table 의 일부만을 접근해서 Logical, Physical I/O 줄임

- Partition 만의 통계정보는 더 정확할 수 있습니다

- local index 는 global index 보다 작습니다

I/O Parallelism 향상

- Partition 은 해당되는 Segment 가 있어 I/O 분리할 수 있습니다

관리작업 범위 축소

- 각 Partition 단위로 다음 명령어를 수행할 수 있습니다

reorg rebuild

update statistics

truncate table

dbcc command

bcp in and out

partition 을 physical device 에 적절하게 배치하는 경우에 관리작업을 하는 시간을 크게 줄일 수 있습니다

Adaptive Server Enterprise15.0 Page: 32 Version: 0.1, 22 Aug 2006

Page 59: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

10. Stored Procedure

10.1 Stored Procedure 를 권고 하는 이유 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 와 Query Tree/Plan 을 생성 하는데 반해, stored procedure 는 이미 이 모든 단계가 진행되어 DB 에 저장되어 있는 상태이므로 DB engine 이 Query compile 을 하는데 소요되는 일들을 할 필요가 없습니다.

모듈화된 procedure 의 이점

모듈화된 procedure 는 에러 핸들링, output formatting, data validation 등의 유리한 이점을 가질 수 있습니다

10.2 Stored Procedure 생성 예 use CUMASTER

go

drop proc CBBA_SP_170BQ001

go

create proc CBBA_SP_170BQ001 (

Adaptive Server Enterprise15.0 Page: 33 Version: 0.1, 22 Aug 2006

Page 60: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

@H_CardNo char(8),

@H_AcctSectCd char(2))

as

SELECT DepoTotAmt, /* 예수금총계 */

SecuSubstAmt, /* 유가대용금 */

RightSubstAmt, /* 권리대용금 */

~

FROM CXMASTER..CUA_ENTRUS_ACCT

(INDEX CUA_ENTRUS_ACCT_X)

WHERE CardNo = @H_CardNo

AND AcctSectCd = @H_AcctSectCd

AT ISOLATION 0

return 0

go

grant all on CBBA_SP_170BQ001 to alluser

go

sp_procxmode CBBA_SP_170BQ001, "anymode"

go

10.3 에러 핸들링 Application name 명시

복잡한 Application 구조에서 장애의 원인 추적 및 운영의 편리를 위하여 모든 Application 에서는 모듈 단위의 name 을 코딩에 포함 합니다.

예) Stored Procedure 의 경우

declare @USPname varchar(30)

set @USPname = “CBBA_SP_CUA_ENTRUS_BAL”

set clientapplname @USPname

예) ESQL/C 의 경우

Adaptive Server Enterprise15.0 Page: 34 Version: 0.1, 22 Aug 2006

Page 61: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

strcpy(appname, APPNAME);

EXEC SQL set clientapplname :applname;

구문에러 체크

모든 절차적 프로그램에서와 마찬 가지로 각 구문 뒤에는 반드시 에러 체크를 수행하여 잘못 수행되는 부분에 대한 적절한 조치를 취할 수 있도록 합니다.

예) T-SQL 에서

insert Table A values(…)

if @@error != 0

return @@error

Stored Procedure 수행 결과 체크

Stored Procedures 체크 누락 시, Stored Procedures 수행에러를 check 하지 못하여, 정상적으로 수행하는 듯하나 결과가 반영되지 못하는 매우 위험한 상황이 발생 할 수 있습니다.

예) EXEC SQL Stored Procedures 실행 후

① Stored Procedures 내 SQL 문의 정상 수행 여부를 check 합니다.

if (sqlca.sqlcode != 0)

② Stored Procedures 의 정상 수행 여부를 check 합니다.

if (ret_code != 0)

예) ESQL/C 에서 Stored Procedure 호출

EXEC SQL EXEC :ret_code = TRMASTER..CBBA_SP_MKT_BOND_CHK

"01", :T01_BondMktOperSect OUTPUT,

:H_Cur_Date OUTPUT, :T01_MktStopResn OUTPUT;

if (sqlca.sqlcode != 0) {

ret_code = sqlca.sqlcode;

tpReturn(iTxInvoked, SE_SEP_RM, ret_code, ED_Msg);

}

Adaptive Server Enterprise15.0 Page: 35 Version: 0.1, 22 Aug 2006

Page 62: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

if (ret_code != 0) {

tpReturn(iTxInvoked, SE_SEP_RM, ret_code, ED_Msg); }

예) Stored Procedure 에서 다른 Stored Procedure 호출

EXEC @error = CUMASTER..USP_CUC_ACCT_MOG

@P_CardNo,

@StdDate,

@ClsSect OUTPUT,

@CredLoanAmt OUTPUT,

@LstkEval OUTPUT,

@LoanEval OUTPUT,

@CredLStkTotAmt OUTPUT

IF @error <> 0

RETURN @error

reserved return status values

values meaning

0 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 interbal inconsistency

-12 Table or index is corrupt

Adaptive Server Enterprise15.0 Page: 36 Version: 0.1, 22 Aug 2006

Page 63: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

-13 Database is corrupt

-14 Hardware error

return code (User-generated return codes)

Procedures 에서 특정 Step 의 Return 값으로 사용합니다

return [int_expression]

10.4 Stored Procedure 와 Transaction mode stored procedure 작성한 transaction mode 와 실행 할 때 transaction mode 가

일치해야 합니다. 변경하고자 할 때는 sp_procxmode 를 사용하면 됩니다. Stored Procedure Transaction mode 는 compile 한 client tool 의 Transaction mode 를 따라 갑니다

① chained mode : stored procedure 가 시작하면 묵시적으로 transaction 이 시작되는 형태

② unchained mode : 기본 mode 로 라인 별로 commit 이 되는 형태의 transaction 모드

③ anymode : 위 두 mode 모두를 수용하는 transaction 모드

Stored Procedure 의 mode 는 C 프로그램의 모드 와 일치 해야 합니다.

즉, C 프로그램이 chained 이면, USP 도 chained 여야 실행이 되고, C 프로그램이 unchained 이면 USP 도 unchained 여야 실행이 됩니다. 만약 이런 부담을 없애고자 한다면 USP 를 anymode 로 사용하면 됩니다

만약 C 프로그램은 chained mode 이고 USP 는 unchained mode 일 경우 다음과 같은 error message 를 만나게 될 것 입니다.

예)

** SQLCODE=(-7713)

** SQL Server Error

** Stored procedure 'sales_proc' may be run only in unchained transaction mode. The 'SET CHAINED OFF' command will cause the current session to use unchained transaction mode.

모드 확인방법

sp 의 모드를 확인하려면 다음과 같이 isql 에서 실행합니다.

Adaptive Server Enterprise15.0 Page: 37 Version: 0.1, 22 Aug 2006

Page 64: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

1> sp_procxmode

2> go

procedure name user name transaction mode

sales_proc dbo Unchained

~

(10 rows affected)

(return status = 0)

본 시스템에서는 anymode 를 사용합니다.

Stored procedure 를 anymode 로 할 경우 C 프로그램의 모드에 상관없이 수행 됩니다.

예)

CREATE PROCEDURE CBBA_SP_SVC_CTL_IN

(@In_SvcGrpCd CHAR(3),

@In_BrCd CHAR(3),

)

AS

DECLARE

@H_Gubun char(1),

@H_BatchEndYn char(1),

@H_BrCd char(3),

..

END

RETURN 0

END

1>grant all on CBBA_SP _SVC_CTL_IN to alluser

2>go

1>sp_procxmode CBBA_SP _SVC_CTL_IN,"anymode"

2>go

Adaptive Server Enterprise15.0 Page: 38 Version: 0.1, 22 Aug 2006

Page 65: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

10.5 Compile Stored procedure 에서 접근하는 테이블이 변경되거나 재 생성 되었을

경우 반드시 recompile 합니다

upgrade 후 반드시 재 생성 합니다.

Stored procedure 의 재 생성은 drop 후 create 혹은 sp_recompile 로 합니다.

예) compile 해야 하는 경우

설명 Update

Statistics

Recompile Drop &

Recreate

Data set 이

변경되었지만

Data 분포는 똑같이

남아 있습니다.

a

Data set 이 변경되었고

Data 분포도 변경

되었다.

a

a

Column 의 추가나

삭제가

되었다.

a

참조된 Object 의 ID 와

Name 이 변경되었다.

a

10.6 Stored Procedure 구현 시 지침 Stored Procedure source 작성 요령

예)

USP 명.sql 로 파일을 생성 합니다

① create table temp table 문

② drop procedure 문

③ create procedure 문

④ business logic

⑤ grant all on USP 명 to alluser

⑥ sp_proxmode USP 명, ‘anymode’

Adaptive Server Enterprise15.0 Page: 39 Version: 0.1, 22 Aug 2006

Page 66: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

CBBA_SP_170BQ001.sql

use CUMASTER

go

drop proc CBBA_SP_170BQ001

go

create proc CBBA_SP_170BQ001 (

@H_CardNo char(8),

@H_AcctSectCd char(2))

as

SELECT DepoTotAmt, /* 예수금총계 */

SecuSubstAmt, /* 유가대용금 */

RightSubstAmt, /* 권리대용금 */

~

FROM CXMASTER..CUA_ENTRUS_ACCT

(INDEX CUA_ENTRUS_ACCT_X)

WHERE CardNo = @H_CardNo

AND AcctSectCd = @H_AcctSectCd

AT ISOLATION 0

return 0

go

grant all on CBBA_SP_170BQ001 to alluser

go

sp_procxmode CBBA_SP_170BQ001, "anymode"

go

Stored Procedure 밖에서 생성된 Work table 참조.

USP_2 가 그 자신 아닌, 같은 세션에서 USP_2 를 호출한 USP_1 이 만든 임시 테이블을 핸들링 할 경우, Optimizer 는 USP_2 compile(Query Tree 생성)시 work table 의 정체를 알지 못 합니다. 따라서 USP2 생성 전에 work table 을 생성하는 step 을 넣어야 합니다.

Adaptive Server Enterprise15.0 Page: 40 Version: 0.1, 22 Aug 2006

Page 67: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

예)

CBBA_SP_SVC_CTL_IN.sql

create table tempdb..worktbl (

~) drop procedure CBBA_SP_SVC_CTL_IN

go

create procedure CBBA_SP_SVC_CTL_IN

as

~

go

multi-depth 구조의 다중 호출 구현을 피합니다.

다중 호출 구조의 stored procedure 구현은 에러 처리나 Transaction 처리에 있어서 불리하고 성능에 유리하지 못하므로 피하는 것이 바람직하다.

Stored Procedure 안에서 Dynamic SQL 구현을 자제 합니다.

Stored Procedure 를 사용하는 이유는 실행 될 때마다 Query compile 을 하지 않고 재 사용하므로 빠른 성능을 얻고자 하는 것인데 Stored Procedure 안에서 Dynamic SQL 을 사용하게 되면 Stored Procedure 안에서 동적으로 생성되는 Query 를 위해서 optimizer 는 매번 compile 과 plan 생성을 수행하게 되므로 빠른 성능을 얻을 수 없게 됩니다.

Adaptive Server Enterprise15.0 Page: 41 Version: 0.1, 22 Aug 2006

Page 68: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

11. OLTP 프로그램

11.1 Multi-rows 조회 Cursor 사용 보다는 Array fetch 를 이용하여 데이터를 조회합니다

일반적으로 ASE 에서는 Cursor 를 사용하는 것보다 Array fetch 하는 것을 권장합니다. 가장 큰 이유는 성능입니다. 다중 사용자 환경의 빠른 성능을 요구하는 본 프로젝트 에서는 가능한 Multi-rows 조회 프로그램에서는 Array fetch 형태의 구현을 권장합니다.

예) Cursor 사용

EXEC SQL DECLARE C1 CURSOR FOR

Select stor_id, ord_num, date from sales at isolation 0;

EXEC SQL OPEN C1;

FOR (;;)

{

EXEC SQL

FETCH C1 INTO :stor_id, :ord_num, :date;

IF ( SQLCA.SQLCODE == 100 )

{PRINTF("NO MORE ROWS TO FETCH. \N");

BREAK ;

}

처리 루틴

}

EXEC SQL CLOSE C1;

EXEC SQL COMMIT;

예) Array fetch with SQL

EXEC SQL BEGIN DECLARE SECTION;

CS_CHAR stor_id[50][5],ord_num[50][21],date[50][50];

EXEC SQL END DECLARE SECTION;

.

EXEC SQL

SELECT stor_id,ord_num,date

Adaptive Server Enterprise15.0 Page: 42 Version: 0.1, 22 Aug 2006

Page 69: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

INTO :stor_id, :ord_num, :date from sales;

처리 루틴

.

.

예) Array fetch with Stored Procedure

EXEC SQL BEGIN DECLARE SECTION;

CS_CHAR stor_id[50][5],ord_num[50][21],date[50][50];

CS_CHAR stor_code[5],sales_date[9];

EXEC SQL END DECLARE SECTION;

EXEC SQL

EXEC SQL EXEC CBBA_SP_SALES :stor_code, :sales_date

into :stor_id, :ord_num, :date;

처리 루틴

.

.

=> 위 소스의 CBBA_SP_SALES stored procedure code

Create proc CBBA_SP_SALES ( @stor_code char(4), @sales_date char(08))

As

Select stor_id, ord_num,date from sales

Where stor_id = @stor_code and sales_date = @sales_date

Return 0

Dirty read 허용.

100% 데이터 정합성을 필요로 하지 않는 multi-rows 조회 프로그램의 경우, isolation level 0 를 사용하면 다른 transaction 과 무관하게 조회가 가능하므로 동시성이 좋으며 사용자 응답시간 단축 효과를 볼 수 있습니다. 그러므로 이러한 약간의 오차가 허용될 수 있는 bulk 조회에 대해서 isolation 0 로 구현 하시기 바랍니다.

예)

select pub_id, pub_name from publishers

at isolation read uncommitted

Adaptive Server Enterprise15.0 Page: 43 Version: 0.1, 22 Aug 2006

Page 70: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

EXEC SQL

SELECT Passwd,DeptBrSect INTO :Br_Passwd, :Br_DeptBrSect

FROM COCOMM..COM_DEPT_BR_INFO (index COM_BR_INFO_PK)

WHERE DeptBrCd = :INH_BrCd

AT ISOLATION READ UNCOMMITTED;

유용한 Search argument(SARGs)를 사용합니다

OLTP 에 영향을 최소화 하기 위하여 반드시 인덱스 사용 여부를 showplan 혹은 planviewer 를 통해 확인합니다. Composite index 의 경우 해당 인덱스를 사용하더라도 모든 칼럼이 참조되는지 확인 해야 합니다.

① Isql 또는 interactive SQL(text) 에서 Query Plan 확인

#isql –Ucbbdbd –Pcbbdbd –SDSECURITY DB 서버에 로그인 합니다.

1>set showplan, noexec on <= plan 보기 설정

2>go

1>select * from sales <= 보고자 하는 Query plan 의 대상 쿼리

2>go

QUERY PLAN FOR STATEMENT 1 (at line 1).

STEP 1

The type of query is EXECUTE.

Executing a previously cached statement.

Total estimated I/O cost for statement 1 (at line 1): 0.

QUERY PLAN FOR STATEMENT 1 (at line 1).

1 operator(s) under root

The type of query is SELECT.

ROOT:EMIT Operator

|SCAN Operator

| FROM TABLE

| sales

| Table Scan.

| Forward Scan.

| Positioning at start of table.

Adaptive Server Enterprise15.0 Page: 44 Version: 0.1, 22 Aug 2006

Page 71: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

| Using I/O Size 4 Kbytes for data pages.

| With LRU Buffer Replacement Strategy for data pages.

Total estimated I/O cost for statement 1 (at line 1): 84.

② Plan viewer 사용 방법

- Dbisql 로 해당 DB 서버에 접속합니다.

- SQL 을 실행합니다

- 화면하단에 plan 버튼을 누르면 실행된 Query 에 대한 plan 을 상세하게 볼 수 있습니다.

필요 데이터 만큼만 Query 합니다

set rowcount 23 => DB 에 접속되어 있는 session 이 종료될 때까지 ‘set rowcount 0’ 이란 명령이 없으면 영향을 미치므로 주의를 기울여야 합니다.

select top 23 => 해당 Query 의 result set 에 제한을 합니다.

예) T-SQL 에서

set rowcount 23 Select a.ReqDate, a.BuyDate

Adaptive Server Enterprise15.0 Page: 45 Version: 0.1, 22 Aug 2006

Page 72: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

from ~

set rowcount 0

or

Select top 23 a.ReqDate, a.BuyDate

from ~

예) ESQL/C 에서

EXEC SQL SET ROWCOUNT 23; EXEC SQL Select a.ReqDate, a.BuyDate

from ~

EXEC SQL set rowcount 0

EXEC SQL Select top 23 a.ReqDate, a.BuyDate

from ~

정확한 오퍼레이터 선택

연속화면 조회와 같이 start key 값과 next key 값을 이용하는 경우 start key 값의 비교 구문은 반드시 > 이 아닌 >= 으로 사용합니다. 이 것은 보다 효과적으로 빠르게 인덱스를 스캔 하게 할 수 있기 때문입니다.

예)

WHERE a.ReqDate >= '111'

11.2 기타 OLTP 구현 지침

11.2.1 Query 구현

유용한 Search argument(SARGs)를 사용합니다.

유용한 SARGs 사용은 ASE 가 Data 를 찾기 위해 Index 사용을 시도할 것이고, 유용한 SARGs 가 없다면 Optimizer 는 Table scan 를 할 것입니다.

pk_TRO_ORD_DTL BrCd, NoSect, OrdNo

TRO_ORD_DTL_idx1 BrCd, OrignOrdNo

TRO_ORD_DTL_idx2 AcctNo, NoSect, ItemCd, OrignOrdNo, OrgOrdNo, OrdNo

Adaptive Server Enterprise15.0 Page: 46 Version: 0.1, 22 Aug 2006

Page 73: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

TRO_ORD_DTL_idx3 EmpNoIn, BrCd

TRO_ORD_DTL_idx4 EmpNoMgr, NoSect, AcctNo, OrdNo

TRO_ORD_DTL_idx5 ItemCd, AcctNo

예) 유용한 인덱스 사용이 없는 잘못된 코딩

where OrignOrdNo = value and NoSect = value

QUERY PLAN FOR STATEMENT 1 (at line 1).

1 operator(s) under root

The type of query is SELECT.

ROOT:EMIT Operator

|SCAN Operator

| FROM TABLE

| TRO_ORD_DTL

| Table Scan.

| Forward Scan.

| Positioning at start of table.

| Using I/O Size 4 Kbytes for data pages.

| With LRU Buffer Replacement Strategy for data pages.

예) index 를 사용하지만 잘못된 코딩

Where BrCd = ‘value’

UERY PLAN FOR STATEMENT 1 (at line 1).

1 operator(s) under root

The type of query is SELECT.

ROOT:EMIT Operator

|SCAN Operator

| FROM TABLE

| TRO_ORD_DTL

| Using Clustered Index.

| Index : pk_TRO_ORD_DTL

| Forward Scan.

조건절에 TRO_ORD_DTL 의 적절한 인덱스 조건이 주어져 있지 않으므로 서 table scan 이 일어납니다. 반드시 자신이 생성한 Query 에 대해서는 plan 을 검증해 주시기 바랍니다

Adaptive Server Enterprise15.0 Page: 47 Version: 0.1, 22 Aug 2006

Page 74: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

| Positioning by key.

| Keys are:

| BrCd ASC

| Using I/O Size 4 Kbytes for index leaf pages.

| With LRU Buffer Replacement Strategy for index leaf pages.

| Using I/O Size 4 Kbytes for data pages.

| With LRU Buffer Replacement Strategy for data pages.

위 예에서 빠른 데이터 접근을 위해서 조건절에 NoSect, OrdNo 를 추가하여 pk 를 사용하게 하든가, OrignOrdNo 를 추가하여 idx1 를 사용하게 하든가, EmpNoIn 를 추가하여 idx3 번을 사용하게 하는 것이 바른 코딩 방법 입니다

예) index 를 바르게 사용한 코딩

Where BrCd = ‘value’ and NoSect = value and OrdNo = value

QUERY PLAN FOR STATEMENT 1 (at line 1).

1 operator(s) under root

The type of query is SELECT.

ROOT:EMIT Operator

|SCAN Operator

| FROM TABLE

| TRO_ORD_DTL

| Using Clustered Index.

| Index : pk_TRO_ORD_DTL

| Forward Scan.

| Positioning by key.

| Keys are:

| BrCd ASC

| NoSect ASC

| OrdNo ASC

| Using I/O Size 4 Kbytes for index leaf pages.

| With LRU Buffer Replacement Strategy for index leaf pages.

| Using I/O Size 4 Kbytes for data pages.

TRO_ORD_DTL 의 pk 인덱스를 사용하기는 하지만, 해당 인덱스는 3 개의 칼럼조합에 의해서 이루어져 있고, 조건 절 기술이 바르지 못해서 한 개 칼럼만을 가지고 인덱스 스캔을 수행하므로 서 포인트 쿼리가 안되어 원하는 데이터를 찾기 위해서 많은 쓸데없는 데이터 스캔이 이루어 집니다

TRO_ORD_DTL 의 pk 인덱스를 모두 사용하여 인덱스 해당 인덱스를 스캔 하므로 가장 빠른 포인트 쿼리가 수행 됩니다

Adaptive Server Enterprise15.0 Page: 48 Version: 0.1, 22 Aug 2006

Page 75: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

| With LRU Buffer Replacement Strategy for data pages.

Where 절에 Index 의 첫(앞부분) Column 을 사용합시다

예)

create index TRO_ORD_DTL_idx2 on TRO_ORD_DTL

( AcctNo, NoSect, ItemCd, OrignOrdNo, OrgOrdNo, OrdNo)

select ~ from TRO_ORD_DTL

where AccNo = value AND

NoSect = value AND

ItemCd = value AND

OrignOrdNo = value AND

OrgOrdNo = value AND

OrdNo = value

Result set 의 제한

화면처리에 알맞은 개수 만큼의 result set 만 return 하게 하거나, 적절한 조건 처리 또는 ‘set rowcount’, ‘select top n’ 등의 방법을 사용하여 서버와 클라이언트 사이의 불필요한 network traffic 을 줄인다.

예)

select top 30 OrdMediaSect, BrCdMgtBr, InBrCd,,,,,,,,

from TRO_ORD_DTL

Where BrCd = ‘value’ and NoSect = value and OrdNo = value

Stored procedure 에서 SARGs 를 Input 파라미터로 사용한다면, 파라미터 Data type 를 Table column 과 일치해야 합니다.

Stored Procedure 활용.

같은 비즈니스 로직을 가진 프로그램이 매우 빈번히 또는 대량의 Data 를 처리하는 Transaction 은 Stored Procedure 로 처리하는 것을 고려합니다. 클라이언트와 서버간의 통신처리 오버헤드의 절감효과와 빠른 성능을 위하여 stored procedure 사용을 권장 합니다

Adaptive Server Enterprise15.0 Page: 49 Version: 0.1, 22 Aug 2006

Page 76: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

SARGs 에서 수학적 처리를 피하라.

예) 잘못 사용한 수학적 처리(pre-15.0 version 에서)

SELECT unit*price*1.1 FROM orders WHERE unit*price*1.1 > 200

위 의 경우 unit 혹은 price 에 인덱스가 있다 하여도 해당 인덱스를 사용하지 못합니다. 따라서 이와 같은 오퍼레이션이 자주 일어난다면 아래와 같이 function index 를 설정하여 사용하도록 합니다.

예) 수학적 처리 Query 해결 방법

CREATE INDEX product_total ON orders (unit*price*1.1)

ROOT:EMIT Operator |SCAN Operator

| FROM TABLE

| orders

| Index : Product_total

| Forward Scan.

| Positioning by key.

| Index contains all needed columns. Base table will not be read.

| Keys are:

| sybfi2_1 ASC

| Using I/O Size 4 Kbytes for index leaf pages.

| With LRU Buffer Replacement Strategy for index leaf pages.

Select list 에서 Column name 를 명시적으로 기술합니다.

만약 Table 에 Column 를 추가하거나 삭제한다면, Stored Procedure 는 정확하게 실행되지 않을 것입니다. 그러므로 Column name 의 정확한 명시는 Column 의 변경을 쉽게 확인 할 수 있습니다.

예)

select * from syslogs

대신에 select xactid, op from syslogs 를 사용

Holdlock 사용.

자신의 transaction 에서 select 한 값을 다른 transaction 으로부터 영향 받지 않고, 처리하고자 하는 경우 hold lock 을 사용합니다.

Adaptive Server Enterprise15.0 Page: 50 Version: 0.1, 22 Aug 2006

Page 77: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

예)

select Amt into :H_Amt from TABLE_A holdlock

where a = H_a;

H_Amt += H_Amt;

UPDATE TABLE_A set

이 경우 Dead Lock 상황을 조심 해야 합니다. 동시 사용자 수가 많고, insert/update/delete 문장이 있는 경우, Deadlock 을 조심 해야 합니다.

SET 명령어는 세션에 대해서 적용이 됩니다.

프로그램에서 set 명령어를 쓰면 해당 세션이 데이터베이스 서버에서 종료 될 때 까지 지속되므로 각 개발자는 특히 주의를 해야 합니다. 프로그램에서 필요에 의해 사용해야 할 경우 해당 명령을 해제(off)하는 코딩을 잊지 말아야 합니다.

예) update 문에서 잘못 처리한 예

아래 예는 30 건의 데이터 조회를 위해서 set rowcount 30 을 설정하였고 TRO_ORD_DTL 의 데이터를 update 하는데 실제로 조건에 맞는 수정되어야 할 건 수가 1000 건인데 set rowcount 가 30 으로 설정되어 있으므로 TRO_ORD_DTL 에 update 역시 30 건만 수행 됩니다

set rowcount 30

Select a.ReqDate, a.BuyDate

from ~

updateTRO_ORD_DTL set AccNo = ~

Where BrCd = ‘value’ and NoSect = value and OrdNo = value

예) set rowcount 의 바른 사용

set rowcount 23

Select a.ReqDate, a.BuyDate

from ~

set rowcount 0

T-SQL 에서 Dynamic SQL 사용을 자제합니다.

Adaptive Server Enterprise15.0 Page: 51 Version: 0.1, 22 Aug 2006

Page 78: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

불가피한 경우를 제외하고는 dynamic SQL 사용을 피합니다. Engine 이 Query 수행을 빠르게 하기 위하여 가능한 static coding 방법을 사용하도록 권장 합니다

Transaction 안에서 DML 을 뒤에 배치합니다.

update, delete 의 문장은 가급적 프로그램의 아래에 grouping 하여 코딩 합니다. check 를 위해 한 번의 select 를 앞에 더 넣는다 할지라도, update/delete 문은 가급적 아래에 grouping 하는 것이 전체 시스템 효율을 위해 좋습니다.

Begin tran

Select …..

Select …..

Delete …..

Insert …..

Update …..

Commit tran

쿼리 문장에 부분조건에 의한 찾기 및 한글 스캔 을 자제하고 코드 찾기에 의한 처리로 바꿉시다

예)

Select id, name from usertbl where address like “%중앙동”(x)

Select id, name from usertbl where address like “중앙동%”(o)

Transaction 내에 사용자 응답을 기다리는 형태의 logic 구사를 금지 합니다.

사용자의 응답이 있을 때 까지 lock 을 점유하고 있을 수 있기 때문입니다.

테이블 접근 순서를 일관성 있게 합시다.

업무별로 주요 테이블들 즉 많은 사용자가 빈번히 접근하는 테이블을 비롯하여 특정 업무를 처리하는 프로그램의 Table 접근 순서를 타 Program 과 비교하여 일관되게 조정 하도록 합시다. Lock 또는 dead lock 을 피할 수 있으며 동시성을 높이므로 성능을 유지할 수 있는 방법 입니다

Adaptive Server Enterprise15.0 Page: 52 Version: 0.1, 22 Aug 2006

Page 79: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

11.2.2 Operator 사용

“>”과”<” 대신에 “>=”과”<=”를 사용합니다.

예)

select * from table_a where x > 3 은 첫 번째 만족되는 Row 를 찾기 위해 x = 3 의 모든 Index page 를 찾는다. 하지만

select * from table_a where x >= 4 는 첫 번째 만족되는 Row 를 직접 찾는다.

“not exists”나 “count(*)” 대신에 “exists”를 사용 합니다

“exists”는 첫 번째 만족되는 Row 를 찾은 다음에 멈추므로 If 문이나 Sub query 에서 빠르게 결과값을 얻을 수 있습니다.

예)

if exists (select postalcode from authors

where postalcode = "94705")

print "Berkeley author"

부정(not exists => exists , != => =)의 비교를 긍정문으로 바꿔라.

=> “not exists” 는”exists” 로 “!=” 은 “=>” 또는 “=” 으로 구현 합니다.

예) 잘못된 사용

If not exists ( Select * From ...)

Begin

... /* statement group */

End

예) 바른 사용

If exists ( Select * From ...)

Begin

Go to exists_label

End

... /* statement group */

exists_label :

“like”나 Wildcard 대신에 “between”을 사용합니다.

Adaptive Server Enterprise15.0 Page: 53 Version: 0.1, 22 Aug 2006

Page 80: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

이것을 쓸 때 주의할 사항은 Dataset 을 분석해야 합니다.

예)잘못된 사용

select cola from table_a where col_b like ‘__A’

예)바른 사용

select cola from table_a where col_b between ‘AAA’ and ‘ZZA’

되지만 col_b 의 데이터 중에 ‘4ZA’이 있으면 같은 결과 값을 얻을 수 없습니다.

Min, Max 함수를 함께 사용 하지 않는다

=>서로 성격이 완전히 다른 함수임

예)

select max(price),min(price) from titles(X)

select max(price) from titles(O)

select min(price) from titles(O)

sub string 의 사용하지 맙시다.

table 설계 시 복합 칼럼 사용을 자제하고 가급적 분해합니다.

11.2.3 Index 사용

Selectivity(선택성)을 위해 Index 를 만든다.

Index 는 Query 를 만족하기 위해 요구되는 가장적은 Row 수를 얻을 수 있도록 합니다. 그러므로 I/O 를 줄일 수 있습니다.

따라서 index 의 첫 번째 칼럼은 selectivity 가 가장 좋은 것을 선택하는 것이 바람직합니다

Covered Query 를 사용합니다.

Non-clustered Index page 의 Leaf Level 에 Query 에 의해서 요구되는 모든 Column 이 포함되어 있는 Query 를 Covered Query 라 합니다. 그래서 Data page 를 읽을 필요가 없게 됩니다.

Index 칼럼 update 를 자제합니다.

Adaptive Server Enterprise15.0 Page: 54 Version: 0.1, 22 Aug 2006

Page 81: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

index 분포의 변동으로 인한 부작용 과 인덱스 관리를 위한 내부 오퍼레이션이 많아지면서 성능 저하의 원인이 될 수 있습니다.

불필요한 중복 인덱스는 제거합니다(생성하지 않는다)

불필요한 인덱스는 DML 처리에 있어서 속도저하를 일으킬 수 있는 요소로 작용하거나 유지보수 작업 시간을 길게 만든다.

n * n Cartesian product 을 피합시다

조인을 사용한 query 의 조건 절에서 outer table 에 있는 인덱스를 사용하지 못한다면 n * n Cartesian product 가 발생하는데 outer table 이든 inner table 이든 데이터가 많을 경우 장애로 이어질 수 있어 이점에 특히 유의해야 합니다. 가장 손쉬운 방법은 outer table 의 인덱스 첫 칼럼은 무조건 상수 값과 비교하게 만들면 최소한 인덱스를 사용할 수 있습니다.

예)

CUA_CARD_X CardNo

CUA_BL_ACCT_X CardNo, AcctSectCd)

FROM CUMASTER..CUA_CARD a,CUMASTER..CUA_BL_ACCT b

WHERE a.CardNo = @IN_CardNo AND

a.CardNo = b.CardNo AND

b.AcctSectCd = @IN_AcctSectCd

AT ISOLATION READ UNCOMMITTED

QUERY PLAN FOR STATEMENT 1 (at line 1).

STEP 1

The type of query is SET OPTION ON.

QUERY PLAN FOR STATEMENT 2 (at line 2).

4 operator(s) under root

The type of query is SELECT.

ROOT:EMIT Operator

|NESTED LOOP JOIN Operator (Join Type: Inner Join)

|

Adaptive Server Enterprise15.0 Page: 55 Version: 0.1, 22 Aug 2006

Page 82: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

| |SCAN Operator

| | FROM TABLE

| | CUA_CARD

| | a

| | Using Clustered Index.

| | Index : CUA_CARD_X

| | Forward Scan.

| | Positioning by key.

| | Keys are:

| | CardNo ASC

| | Using I/O Size 4 Kbytes for index leaf pages.

| | With LRU Buffer Replacement Strategy for index leaf pages.

| | Using I/O Size 4 Kbytes for data pages.

| | With LRU Buffer Replacement Strategy for data pages.

|

| |RESTRICT Operator

| |

| | |SCAN Operator

| | | FROM TABLE

| | | CUA_BL_ACCT

| | | b

| | | Using Clustered Index.

| | | Index : CUA_BL_ACCT_X

| | | Forward Scan.

| | | Positioning by key.

| | | Keys are:

| | | CardNo ASC

| | | AcctSectCd ASC

| | | Using I/O Size 4 Kbytes for index leaf pages.

| | | With LRU Buffer Replacement Strategy for index leaf pages.

| | | Using I/O Size 4 Kbytes for data pages.

| | | With LRU Buffer Replacement Strategy for data pages.

Adaptive Server Enterprise15.0 Page: 56 Version: 0.1, 22 Aug 2006

Page 83: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

필요하다면 인덱스 힌트를 사용할 수 있습니다.

예)

SELECT CardNo, AcctSectCd, BalNo, count(*) Cnt

FROM USER_TABLE (INDEX INDEX_X)

11.2.4 데이터 타입 사용

Numeric 보다는 bigint, smallint, int, tinyint 사용합니다.

데이터 타입 일치

조건 절에 사용된 변수들은 데이터 타입이 데이터 테이블의 칼럼과 반드시 일치 시킨다. 만약 상이할 경우는 covert 문을 사용하여 일치 시킨다.

인덱스의 데이터 타입은 고정길이 타입으로 선언합니다

인덱스의 데이터 타입으로 숫자, 날짜 등은 사용하지 않는다

데이터 타입이나 길이가 다른 칼럼의 비교나 조인을 하지 않는다.

11.2.5 Transaction

가능한 Transaction 은 짧게 유지합니다

Transaction 안에서 입력 값을 기다리는 처리는 피합니다

Chain mode transaction 사용은 하지 않는다

Exclusive lock 을 가진 Transaction 은 가능한 작고 짧게 유지 합니다

만약 ASE 의 특정 Object 에 대해 Exclusive Lock 이 있다면, Transaction 동안에 그 Object 를 요구한 다른 User 들은 Block 이 걸린 상태로 있기 때문입니다.

Adaptive Server Enterprise15.0 Page: 57 Version: 0.1, 22 Aug 2006

Page 84: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

12. Batch 프로그램

12.1 Stored Procedure 활용 배치 프로그램의 데이터 액세스 부분은 가급적 Stored Procedure 로 구현하는 것을 권장합니다. Stored Procedure 에서 처리되는 DML 또는 Query 가 ESQL/C 에서 수행되는 것보다 훨씬 빠르기 때문 입니다. 즉 Query 들을 run time 에 compile 하는 것 보다는 Stored Procedure 와 같이 compile 되어 query tree 상태로 저장되어 있는 프로그램을 호출하는 방식이 network 부담이나 run time 에 Query compile 에 대한 엔진 부담을 줄여 줄 수 있어 성능 면에서 좋은 결과를 얻을 수 있습니다

AP (service)with business logic

DECLATE C1 CURSOR FOR SELECT A.a A.b FROM TABLE-A;OPEN C1;WHILE (1) {FETCH C1;INSERT TABLE-B;INSERT TABLE-C;UPDATE TABLE-D;}

AP (service)with USP call

USPwith business logic

DECLATE C1 CURSOR FOR SELECT A.a A.b FROM TABLE-A;OPEN C1;WHILE (1) {FETCH C1;INSERT TABLE-B;INSERT TABLE-C;UPDATE TABLE-D;}

ESQL/C Application 구조 Stored Procedure Application 구조

AP (service)with business logic

DECLATE C1 CURSOR FOR SELECT A.a A.b FROM TABLE-A;OPEN C1;WHILE (1) {FETCH C1;INSERT TABLE-B;INSERT TABLE-C;UPDATE TABLE-D;}

AP (service)with USP call

USPwith business logic

DECLATE C1 CURSOR FOR SELECT A.a A.b FROM TABLE-A;OPEN C1;WHILE (1) {FETCH C1;INSERT TABLE-B;INSERT TABLE-C;UPDATE TABLE-D;}

ESQL/C Application 구조 Stored Procedure Application 구조

12.2 Cursor 사용

12.2.1 Non scrollable Cursor

ASE 가 제공하는 기본 cursor 로 결과 set 을 오로지 앞에서 뒤로 scan 할 수 있는 cursor 입니다. 단순히 fetch 에 의해서 다음 데이터를 읽을 수 있는 cursor 입니다.

예)

declare business_crsr cursor

for select title, title_id

from titles

where type = "business"

for update of price

Adaptive Server Enterprise15.0 Page: 58 Version: 0.1, 22 Aug 2006

Page 85: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

12.2.2 Scrollable cursor

커서의 결과 셋 안에서 커서의 위치를 패치 구문에서 next, prior, first, last, absolute, relative 등을 이용하여 자유자재로 설정할 수 있는 기능으로 커서가 오픈 되어 있는 한 결과 셋의 어떠한 데이터도 가져올 수 있거나 여러 번 검색할 수 있는 편의성을 제공합니다. Scrollable cursor 는 read only 입니다.

12.2.3 Sensitivity in Cursor Sensitive

Sensitive cursor 의 경우는 base table 의 데이터 변화를 cursor 를 fetch 하면서 볼 수도 또는 보지 못 할 수도 있습니다. 즉 cursor 에서 현재 fetch 된 rows 를 제외 한 부분에 대한 base table 의 변화를 cursor 에서 볼 수 있습니다. 그러나 현재 fetch 되어 worktable 에 저장되어 있는 데이터 값에 대한 base table 의 변화는 cursor 에 반영되지 않습니다.

Insensitive

Insensitive cursor 는 cursor open 시 결과 set 을 worktable 에 복사합니다. 따라서 worktable 에 복사가 끝나면 소스 테이블에서 hold lock 을 해제합니다. 그리고 복사된 worktable 에서 fetch 되므로 base table 에 어떠한 데이터 변화에도 cursor 는 영향을 받지 않습니다. 따라서 insensitive cursor 는 read only cursor 입니다.

12.2.4 Cursor 구현 지침

반드시 cursor 를 써야 한다면 한번에 fetch 할 수 있는 rows 를 조절 합시다.

아래와 같이 프로그램에서 기술할 경우 fetch 때마다 20 rows 씩 데이터베이스 서버에서 Client 로 데이터를 가지고 오게 되므로 network traffic 을 줄일 수 있어서 좋은 성능을 얻을 수 있습니다. 물론 fetch 한 20 rows 를 처리하는 루틴의 코딩은 있어야 합니다.(Default 는 1 row 입니다)

예) SQL 에서

set cursor rows 20 for authors_crsr

예) ESQL/C 에서

exec sql open cursor_name row_count = 20;

server side cursor 를 사용하세요!!!!!

Adaptive Server Enterprise15.0 Page: 59 Version: 0.1, 22 Aug 2006

Page 86: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

Client side cursor 사용은 응용프로그램 성능을 떨어 드립니다. 즉 cursor open 시 ASE 는 cursor 를 compile 하고 plan 을 만들어 실행하게 되므로 server side cursor 즉 stored procedure 에 포함되어 있는 compile 되어 저장되어 있는 커서를 실행하는 것보다 많은 성능 차이를 갖습니다. 따라서 커서로 응용프로그램을 구현할 경우 server side cursor 를 권고 합니다.

Cursor 선언 시 Cursor 의 사용 목적 또는 dirty read 옵션을 반드시 선언 합시다

생략할 경우 “for update”로 선언 되므로 Lock 의 문제가 발생 할 수 있습니다. 동시성을 보장하기 위해서 for read only 또는 at isolation 0 또는 insensitive option 을 사용합시다

예) Row 를 읽기만 할 경우

declare authors_crsr cursor for

select au_id, au_lname from authors

where state = ‘CA’

for read only

이 경우 cursor 가 open 되어 있는 동안 base table 에 shared lock 을 잡습니다.

예) dirty read 할 경우

declare authors_crsr cursor for

select au_id, au_lname from authors

where state = ‘CA’

at isolation 0

base table 에 아무런 lock 을 발생 시키지 않습니다

Cursor 에서 base table 을 읽으면서 update 하는 프로그램 구현은 이렇게 하세요.

아래와 같이 소스 테이블의 데이터를 임시 테이블에 저장한 다음 이 임시 테이블을 소스 테이블로 하여 cursor 를 생성하였는데 15.x version 부터는 cursor 선언 시 insensitive option 을 사용할 경우 아래와 같은 효과를 얻을 수 있습니다. 즉 내부적으로 cursor 가 open 되는 시점에 소스 테이블이 worktable 로 복사되어 소스 테이블은 lock 이 해제되며, 다른 세션에서 변경된 소스 테이블의 내용이 cursor 가 오픈 되어 있는 동안 반영되지 않습니다

Adaptive Server Enterprise15.0 Page: 60 Version: 0.1, 22 Aug 2006

Page 87: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

예) 개선 전(12.x)

DECLATE C1 CURSOR FOR

SELECT A.a A.b FROM TABLE-A;

OPEN C1;

WHILE (1) {

FETCH C1;

INSERT TABLE-B;

INSERT TABLE-C;

UPDATE TABLE-A WHERE ...;

}

예)개선 후(12.x)

SELECT * INTO #TEMP-TABLE FROM TABLE-A Where..;

DECLATE C1 CURSOR FOR

SELECT A.a A.b FROM #TEMP-TABLE;

OPEN C1;

WHILE (1) {

FETCH C1;

INSERT TABLE-B;

INSERT TABLE-C;

UPDATE TABLE-A WHERE ...;

}

예)개선 후(15.x)

DECLATE C1 INSENSITIVE CURSOR FOR

SELECT A.a A.b FROM TABLE-A;

OPEN C1;

WHILE (1) {

FETCH C1;

INSERT TABLE-B;

INSERT TABLE-C;

UPDATE TABLE-A WHERE ...;

Adaptive Server Enterprise15.0 Page: 61 Version: 0.1, 22 Aug 2006

Page 88: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

}

12.3 기타 배치 지침 하나의 transaction 에서 처리되는 데이터 건수를 조절

DML 이든 Query 든 배치 프로그램이 수행되면서 처리되는 데이터의 양은 조건에 따라서 항상 유동적일 수 있습니다. 만약에 수 백만 건의 데이터를 한번에 update/delete 하는 배치 프로그램이 수행될 경우 transaction 로그가 Full 되거나 너무 많은 수의 locking 현상으로 다른 작업에 영향을 줍니다이든지, 장애를 일으키는 등 부작용이 발생할 수 있어 처리 건수 즉 commit 건수를 나누어 처리하는 것을 권고 합니다.(5000 건 단위 commit)

Cursor 로 구현된 프로그램은 deallocate cursor/close cursor 를 정확히

Cursor 로 프로그램을 구현 할 때 , 정상종료 시 혹은 에러/장애 발생 시 close cursor 를 하지 않고, 종료되는 경우 메모리가 해제 되지 않으므로 Cursor 가 Open 되어있는 상태를 유지하므로 같은 이름의 Cursor 가 생성되지 않는 다든가 lock 이 해제되지 않아 문제가 발생하게 됩니다. 따라서 프로그램 종료 시에는 반드시 close cursor, deallocate cursor 를 프로그램 종료 루틴에 넣어 주어야 합니다

Tempdb 사용 후 drop table 명령을 빠뜨리지 맙시다

많은 데이터를 다루는 batch 프로그램의 경우 중간 단계의 데이터 가공 등을 목적으로 tempdb 에 임시 테이블(#이 붙은 임시테이블) 을 생성하는데 원래는 tempdb 에 생성된 테이블 들은 접속했던 session 이 끝나면 자동으로 삭제되는데 구조상 session 을 종료하지 않는 프로그램, 에러에 의해서 비정상 종료 시 임시 테이블이 그대로 tempdb 에 쌓이게 되는데 이러한 문제는 결국 tempdb 의 full 등과 같은 장애의 원인이 될 수 있습니다. 따라서 임시 테이블을 사용하는 응용 프로그램 에서는 반드시 정상이든 비 정상이든 이 임시 테이블을 삭제하는 루틴을 빠뜨리지 맙시다

필요하다면 optimizer 를 선택 합시다

대량을 데이터를 접근하거나 복잡한 Query 를 수행할 경우 기본 optimizer 보다는 DSS 업무에 적합한 query 를 만들어 내는 optimizer 를 선택하는 것이 배치 성능을 높이는데 도움이 될 것 입니다.

① 세션 수준

set plan optgoal allrows_dss

Adaptive Server Enterprise15.0 Page: 62 Version: 0.1, 22 Aug 2006

Page 89: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

② Query 수준

select * from A order by A.a plan "(use optgoal allrows_dss)"

Adaptive Server Enterprise15.0 Page: 63 Version: 0.1, 22 Aug 2006

Page 90: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

13. Online-Batch 프로그램

온라인 배치 프로그램은 배치 프로그램의 일종이며, 기본 구조는 배치 프로그램과 유사하나 일반 배치 프로그램과는 다르게 온라인(OLTP) 프로그램과 같은 시간대에 수행되므로 일반 배치프로그램과 반드시 구별하여 프로그래밍 해야 합니다.

13.1 구현 지침 온라인배치 프로그램은 다른 OLTP 서비스 환경을 충분히 숙지한 후

작성 해야 합니다.

항상 최소 단위의 데이터 처리(commit)를 목표로 프로그램을 작성합니다. 즉 OLTP 프로그램에 미치는 영향을 고려 합니다.( 1 row 단위 commit 유도)

가능한 장 종료 후에 온라인 배치를 수행할 수 있도록 유도합니다.

상황에 따라 강제 종료 될 수 있으므로 재 수행이 가능하도록 구현 되어야 합니다

중요 테이블을 변경하는 OLB 의 경우 반드시 시스템 운영자의 확인을 통해 수행될 수 있는 절차를 마련해야 합니다

Adaptive Server Enterprise15.0 Page: 64 Version: 0.1, 22 Aug 2006

Page 91: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

14. 원격 데이터 접근

14.1 Component Integration Service 란 ASE 의 CIS 란 원격에 있는 데이터베이스의 오브젝트를 로컬에 있는 오브젝트 인 것과 같은 접근 성을 제공하는 engine 차원의 기능 입니다. 즉 원격의 테이블이나 stored procedure 를 호출할 수 있는 편리함을 제공합니다.

14.1.1 Proxy Table 생성

Proxy Table 이란 Remote Server 에 있는 Stored Procedure 나 View, Table 을 Mapping 해 놓은 Local Table 을 칭합니다.

14.1.1.1 Manual 로 생성

① Remote Object 의 저장위치와 이름 정의

Syntax) sp_addobjectdef tablename, “objectdef” [,”objecttype”]

② Proxy Table 에 Remote Object Map

Syntax) create existing table table_name (column_list)

14.1.1.2 Sybase central 을 이용한 생성

① Proxy Table 을 추가할 Database 선택

② Proxy Table Container 를 클릭

Adaptive Server Enterprise15.0 Page: 65 Version: 0.1, 22 Aug 2006

Page 92: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

③ Add proxy table 을 더블클릭. Create a Proxy Table wizard 가 시작 됩니다.

④ Proxy table 의 기초가 되는 Remote Object 의 종류 선택

⑤ Remote Server 및 Database 선택

⑥ 원하는 Object 을 선택하여 Table 내용 변경 후 저장합니다.

14.1.2 Remote Procedure call

Remote Stored Procedure 의 속성은 일반 Stored Procedure 와 유사합니다. 단지, Stored Procedure 가 원격의 서버에 있을 뿐입니다

DBMS 간의 통신으로 이루어지므로, 개발자의 입장에서는 위치에 투명하게 실행할 수 있어 Application 이 간편 합니다

Sybase DBMS 에서 transaction 의 2PC 를 보장하므로, transaction 및 데이터의 정합성을 보장할 수 있습니다.

2PC 의 보장은 성능과 밀접한 연관 있습니다. 따라서 구현 시 주의 하여야 합니다

예) 원격의 서버에 있는 stored procedure 호출

EXEC SQL EXEC

:rep_code = INFROM.TRMASTER..USP_TRS_CALS_FEE

Adaptive Server Enterprise15.0 Page: 66 Version: 0.1, 22 Aug 2006

Page 93: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

예) 로컬에 있는 Stored Procedure 호출

EXEC SQL EXEC

:ret_code = TRMASTER..USP_TRS_CALC_FEE

14.1.3 외부 파일 접근

Adaptive Server Enterprise 는 File system 에 있는 files 을 SQL 에서 직접 접근할 수 있는 환경을 제공 합니다. 단 insert, select , truncate 만 허용 합니다

예)

create existing table Fname (

column1 int ,

column2 char(10),

column3 varchar(1024) null

) external file at "/unify/sybase15/dba/Fname.log" column delimiter "|"

위의 경우 데이터베이스 테이블이 아니고 /unify/sybase15/dba/Fname.log 라고 하는 외부 파일에 SQL 에서 직접 read, write 를 수행 합니다.

14.1.4 CIS 구현 지침

원격의 서버로부터 대량 데이터 조회는 삼가 합니다.

CIS(DB link)는 원격 테이블 참조 시 서버 대 서버의 통신을 통해서 데이터를 접근하므로 network 이나 원격의 I/O 등에 영향을 미치므로 대량의 데이터 참조는 두 시스템 모두에 좋지 않을 수 있습니다.

원격 테이블과 로컬 테이블의 조인이 필요한 경우

원격 테이블의 데이터 량을 최대한 줄이고 #temp table 로 가져와서 로컬 테이블과 #temp table 과 조인을 수행하는 방식으로 프로그램 합니다

예)

/* 원격의 테이블을 #temp table 로 가져오는 루틴*/

SELECT a.CustID, a.CustName, b.ProSale, ~ INTO #temp FROM CustMaster a, AccHist b

WHERE ~

Adaptive Server Enterprise15.0 Page: 67 Version: 0.1, 22 Aug 2006

Page 94: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

/* #temp table 과 local table 과 조인 수행 루틴 */

SELECT a.CustID, a.CustName, b.ProSale, ~ FROM #temp a, CUA_CARD b

WHERE a.CustID = b.CustID

***** #temp table 을 사용하고 반드시 drop 하는 루틴을 넣어야 합니다. 정상종료 혹은 에러에 의해서 빠지는 모든 루틴에 #temp table drop 을 삽입하여 주시기 바랍니다

Remote join 구현을 하지 맙시다

특히 local table 과 remote table 간의 join 은 성능에 치명적일 수 있으므로 삼가 합니다.

로컬 서버에 직접 접속합시다.

불가피하게 많은 양의 remote server 의 데이터를 핸들링 할 경우 직접 해당 서버로 접속할 것을 권고 합니다. 다음 절의 multi session 연결 부분을 참고 하시기 바랍니다

proxy table 은 생성하지 않는 것을 기본 원칙으로 합니다

PRC 는 허용하지 않는 것을 기본원칙으로 합니다

14.2 Multi-connection 연결 업무 영역별로 분리되어 있는 DB 서버간 데이터 Sync 는 EAI, Replication, CIS 혹은 이번 장에서 설명하는 Multi-connection 접속 방법을 사용할 수 있습니다. 이번 장에서 설명하는 multi- connection 접속 방법은 local 서버와 remote 서버의 데이터를 동기적인 방식(synchronous processing)으로 처리 하기는 하지만 Global 정합성을 보장하기 위해서는 별도의 application 보완이 필요합니다. 따라서 원장서버의 경우 remote 서버의 데이터 변경 처리 활용을 권장하지 않습니다.

14.2.1 ESQL/C 에서 구현 예

remote 서버를 select 할 경우만 활용하도록 권고합니다. local 서버에서만 변경(I/U/D) 처리를 하는 경우는 관계 없습니다.

예 1)

Adaptive Server Enterprise15.0 Page: 68 Version: 0.1, 22 Aug 2006

Page 95: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

EXEC SQL BEGIN DECLARE SECTION;

CS_CHAR user[16];

CS_CHAR passwd[16];

CS_CHAR name;

CS_INT value, test;

CS_CHAR server_1[BUFSIZ];

CS_CHAR server_2[BUFSIZ];

EXEC SQL END DECLARE SECTION;

...

strcpy (server_1, "sybase1");

strcpy (server_2, "sybase2");

strcpy(user, "my_id");

strcpy(passwd, "mypass");

EXEC SQL CONNECT :user identified by :passwd

at connection_2 using :server_2;

EXEC SQL CONNECT :user identified by :passwd using :server_1;

/* 이 문장들은 로컬 서버 server_1 에서 수행이 되는 부분 입니다 */

EXEC SQL SELECT ROYALTY INTO :value FROM AUTHORS WHERE author = :name;

if (sqlca.sqlcode != 0) {

EXEC SQL DISCONNECT server-2;

~

}

/* 이 문장들은 원격 서버 server_2 에서 수행이 되는 부분 입니다 */

/* remote 서버에서 SQL 을 수행할 때에는 'AT' 를 사용합니다. AT 를 생략한 경우는, default 서버의 테이블로 access 됨을 유의 합시다*/

EXEC SQL AT server-2

SELECT a,b,c FROM COM_SEC_TAB WHERE ...;

if (sqlca.sqlcode != 0) {

~

/* remote 서버에서의 작업이 정상 종료 시 반드시 remote 서버에 대해 disconnect 합니다 */

로컬 데이터베이스 서버 connect string 입니다

원격 데이터베이스 서버 connect

i 입니다

Adaptive Server Enterprise15.0 Page: 69 Version: 0.1, 22 Aug 2006

Page 96: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

EXEC SQL DISCONNECT server-2;

~

}

/*default connection 을 server_1 로 바꾸고자 할 경우 사용 합니다*/

EXEC SQL SET CONNECTION server_1;

EXEC SQL DISCONNECT {ALL};

14.2.2 Multi connection 구현 시 주의사항

반드시 connection 을 종료하는 DISCONNECT 문을 기술한다.

프로그램의 종료는 반드시 ALL option 을 사용 합시다. session 이 종료되면 진행 중이던 transaction 은 rollback 되며 생성되었던 임시 테이블 들은 자동으로 없어지고 locks 은 해제 됩니다. 그리고 disconnect 문이 현재 진행 중이던 transaction 을 commit 하지는 않는다는 것을 기억 하시기 바랍니다

예)

exec sql disconnect {connection_name | current | DEFAULT| all}

Online transaction 처리는 삼가 해 주십시오.

매우 빈번히 처리하는 online transaction 처리의 경우 로컬서버에서 보다 오랫동안 원격서버에 lock 을 유발할 수 있어 주의를 하여야 합니다

Adaptive Server Enterprise15.0 Page: 70 Version: 0.1, 22 Aug 2006

Page 97: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

15. Optimization

Adaptive Server Enterprise 는 급변하는 기업 환경에서 다양한 workload 에서 최상의 성능을 발휘하기 위해 목적 기반의 Query Optimizer 를 제공 합니다. 일반적인 RDBMS 가 지원하는 OLTP 업무뿐만 아니라 DSS 업무를 효과적으로 지원하기 위한 옵션을 제공하며, 혼합된 작업(Mixed workload) 에서의 성능을 위한 옵션 또한 제공 합니다.

15.1 Optimization Goals allrows_oltp

오직 OLTP Query 의 성능을 위한 plan 을 생성 합니다. 즉 nested loop joins 을 수행하며 어떠한 상황에서도 병렬처리를 하지 않습니다. 따라서 순수 OLTP 어플리케이션 개발이나 ISVs 에 유용한 최적화 방법이라고 할 수 있습니다

Plan 방법=> nested loop joins only, no parallelism

allrows_mix : 기본 goal

OLTP 와 operational DSS Query 에 유용한 plans 을 생성 합니다. 즉 Query 의 형태에 따라서 Optimizer 는 allrows_oltp 로 수행할 것인지, allrows_dss 로 수행 할 것인지 판단 합니다.

Plan 방법=> allrows_oltp + merge joins, +parallelism

DSS 업무에 적합한 Query plan 을 생성하는 option 으로 대량의 데이터를 조인하는 복잡한 query, sum, distinct, order by , group by 등 많은 데이터를 다루는 query 에서는 빠른 성능을 기대할 수 있는 optimize 기법 입니다.

Plan 방법=> allrows_mix +hash joins

15.2 Goals 선택방법 서버 widesp_configure 'optimization goal', 0, 'allrows_oltp'

세션 차원의 설정 set plan optgoal allrows_oltp

Query 차원의 설정 SELECT * FROM A ORDER BY A.A plan "(use optgoal allrows_dss)"

Adaptive Server Enterprise15.0 Page: 71 Version: 0.1, 22 Aug 2006

Page 98: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

15.3 Join 의 종류

15.3.1 Nested Loop Join

Nested Join 은 OUTER TABLE 의 1 ROW 당 INNER TABLE 의 모든 ROW 를 MATCH 하는 것입니다. INNER TABLE 과 JOIN COLUMN 에 INDEX 가 있는 경우 효과적입니다. Ordering 을 필요로 하지 않는 간단한 OLTP 에 유용하며, Nested loop 는 showplan output 에서 'nested iteration' 으로 보여집니다.

15.3.2 Merge Join

MJ 는 조인하려는 두 테이블을 동시에 SCAN 하면서 값을 ROW 단위로 비교하여 결과 셋을 만들고, order 된 상태의 input 을 받아 join 을

Adaptive Server Enterprise15.0 Page: 72 Version: 0.1, 22 Aug 2006

Page 99: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

수행하는데, merge join key 에 대한 order 가 되어있는 경우에는

효율적이나 그렇지 않은 경우에는 sort 한 worktable 을 만드는 데에

효율이 떨어질 수 있습니다.

JOIN 할 테이블의 SORT 여부에 따라 4 종류의 MERGE JOIN 이 생성 됩니다

15.3.3 Hash Join

Hash Join 은 다른 조인 방법들 보다 더 많은 runtime resource 를 사용 하는데 상대적으로 row 가 많은 table 의 join 과 유용한 index 가 존재하지 않는 column 의 join 에 좋습니다. 이 해쉬 조인의 힌트 방법으로는 “set hash_join 1” 으 로 활성화 합니다. HASH TABLE 은 PROCEDURE CACHE 에 만들어 지기 때문에 해쉬 조인을 응용프로그램에서 많이 사용할 경우 DBA 는 procedure cache 영역 튜닝을 고려해야 합니다

Adaptive Server Enterprise15.0 Page: 73 Version: 0.1, 22 Aug 2006

Page 100: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

16. Adaptive Server Enterprise 접근하기

16.1 ASE 접근하기 위한 환경 Adaptive Server Enterprise 에 접근하기 위해서는 최소한 다음과 같은

환경이 설정되어 있어야 Client 가 접근할 수 있습니다.

① SYBASE : ASE home directory 를 명시한다

② SYBASE_ASE : ASE-15_0 directory 에 관한 directory

③ SYBASE_OCS : Client lib 및 tools 에 관한 directory

④ SHLIB_PATH : shared library path

⑤ DSQUERY : Default Server name

⑥ LD_LIBRARY_PATH : ld library directory

⑦ SYBASE_SYSAM : licenses file 관련 directory

⑧ interfaces file : 서버에 대한 IP address 와 ports 가 저장되어 있는 파일

⑨ Path : 실행 파일들에 대한 path 설정

기타 ASE 관련 툴을 사용하기 위해서는 ASE home 아래에 있는 profile 을 참조하여 접속하려고 하는 client profile 에 추가해 주어야 합니다.

UNIX 의 경우, 8 번 항목에 기술된 interfaces 파일이 반드시 client home directory 에 있어야 합니다. 만약 자신이 접속하려고 하는 서버 엔트리가 interfaces file 에 없을 경우는 UNIX 의 경우 vi 를 이용하여 interfaces 파일을 편집 하거나 dscp utility 를 사용하여 추가하면 됩니다.

WINDOWS 의 경우, \Sybase\ini\sql.ini 파일에 자신이 접속하려는 서버 엔트리가 있어야 합니다. 만약 없을 경우 windows 의 Sybase folder 에 connectivity>Open Client Directory Services Editor 를 선택하여 서버 엔트리를 등록하여 주면 서버에 접속할 수 있습니다.

16.2 isql 사용하기 isql 에서 SQL 문 실행하기

Adaptive Server Enterprise15.0 Page: 74 Version: 0.1, 22 Aug 2006

Page 101: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

isql 은 ASE 에 접속하여 모든 명령을 수행할 수 있는 text 형태의 utility 입니다. isql 에서 SQL 을 실행하기 위해서는 prompt 에서 문장을 완성한 다음 마지막 문장에 ‘go’를 입력하고 Enter 를 치면 해당 SQL 또는 명령이 ASE 에서 실행 됩니다. 즉 isql 은 unchain mode 이므로 ‘go’ 명령은 commit tran 을 의미하게 됩니다.

예)

isql –Uabcdbd –Pabcdbd –SDSECURITY

1> use pubs2 => use 문을 사용하여 데이터베이스를 바꿉니다

2> go

1> select *

2> from authors

3> where city = "Oakland"

4> go

1>exit or quit => 중단하고 빠져나가기

vi editor 와 같이 사용하기

isql 을 사용하던 중 typing miss 에 의해 지금까지 type 했던 문장을 고치고자 할 경우 isql prompt 상에서 vi 를 치면 현재까지 type 했던 문장이 vi 화면에 나타납니다. 완성된 후에는 파일을 저장하듯 ‘wq’를 치게 되면 isql 화면으로 전환 됩니다.

예)

1> select *

2> from authors

3> where city = "Oakland"

4> vi

isql 에서 외부 파일 불러 들이기

isql –Usa –P

1>:r /tmp/sample.sql

scripts 실행 시키기

script 를 isql 과 실행 할 수 있는 방법을 소개하도록 하겠습니다. 방법을 ‘-i’ 옵션을 사용하는 방법과 ‘<’를 사용하는 방법이 있습니다.

Adaptive Server Enterprise15.0 Page: 75 Version: 0.1, 22 Aug 2006

Page 102: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

예)

isql –Usa –P –SDSECURITY –i script_file

isql –Usa –P –SDSECURITY < script_file

물론 script file 의 내용은 올바를 syntax 즉 구문과 ‘go’ 문을 포함한 isql 에서 실행 가능한 형태를 갖추고 있어야 합니다.

scripts 로 result set 뽑아내기

결과를 out file 로 받아내는 방법을 설명하도록 하겠습니다. 방법은 ‘-o’ 옵션을 사용하거나 ‘>’를 사용 할 수 있습니다.

예)

isql –Usa –P –SDSECURITY –i script_file -o out_file

isql –Usa –P –SDSECURITY < script_file > out_file

script file 의 내용이 ASE 에서 실행되어서 나온 결과를 out_file 안에 기록 합니다.

16.3 Bcp 사용 데이터 추출/적재 Table 단위로 Backup 을 하거나 타 DBMS 또는 SAM file 의 data 를 ASE 의 table 로 또는 그 반대로 data 를 옮길 경우에 bcp 를 사용하여 간단히 수행 할 수 있습니다. bcp 는 table 에 data 를 넣는 경우(in)와 table 의 data 를 꺼내는 경우(out)로 구분할 수 있습니다.

bcp 를 하기 위해서는 해당 db 에 “select into/bulkcopy/pllsort” 옵션이 설정되어 있어야 합니다.

1> sp_helpdb CBBDB

2> go

name db_size owner dbid created status

CBBDB 16000.0 MB cbbdba 15 Aug 30, 2006 select nto/bulkcopy/pllsort,

CBBZ_BOND_ITEM.out 에 저장되어 있는 text file 을 CBBDB..CBBZ_BOND_ITEM 테이블에 Load 하는 예제 입니다

bcp CBBDB..CBBZ_BOND_ITEM in CBBZ_BOND_ITEM.out -c -Ucbbdba -Pcbbdba -b10000

Adaptive Server Enterprise15.0 Page: 76 Version: 0.1, 22 Aug 2006

Page 103: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

-b10000 은 10000 건 씩 commit 을 수행한다는 것을 의미합니다. 만약 이것을 기술하지 않으면 모든 데이터를 load 하고 commit 하므로 index 가 걸려있는 테이블의 경우는 transaction log 를 쓰기 때문에 속도도 떨어지고 transaction log full 의 가능성도 있을 수 있습니다. 데이터 량에 따라서 commit count 를 설정하여 bcp in 을 하시기 바랍니다.

CBBDB..CBBZ_BOND_ITEM 테이블에 저장되어 있는 데이터를 bcp 를 이용하여 CBBZ_BOND_ITEM.out file 로 text 형식으로 추출하는 예제 입니다.

bcp CBBDB..CBBZ_BOND_ITEM out CBBZ_BOND_ITEM.out -c -Ucbbdba -Pcbbdba

Adaptive Server Enterprise15.0 Page: 77 Version: 0.1, 22 Aug 2006

Page 104: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

17. Tools

17.1 Sybase Central ASE 의 기본 제품 구성 중 PC client 제품 안에는 Sybase 가 제공하는 DBMS 제품에 대한 통합 관리 툴인 Sybase Central 을 제공 합니다. 관리자 혹은 개발자는 Central 을 통해 Sybase ASE 에 대한 접근 및 관리를 손쉽게 수행 할 수 있을 뿐 아니라 interactive SQL, Plan viewer, Job Scheduler 등 과 같은 Sybase 툴들 그리고 일반 응용프로그램을 구동 할 수 있게 하는 환경을 제공 합니다. 한글 값 깨짐을 방지하기 위하여 해당 서버에 처음 접속 할 때 나타나는 log in 화면에서 사용자 ID, 패스워드와 함께 character set(eucksc)과 language(Korean)를 맞추어 주어야 합니다(Sybase central 에 접속할 때도 마찬가지 입니다)

17.2 ODBC 설정 ① Sybase central 의 왼쪽 창에서 Adaptive Server Enterprise 라고 하는 icon 을

click 하면 오른쪽 panel 에 server groups, servers, utilities tab 이 보이는데 utilities 를 click 하여 Add New Utility 를 선택합니다.

Adaptive Server Enterprise15.0 Page: 78 Version: 0.1, 22 Aug 2006

Page 105: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

② C:\WINDOWS\system32\odbcad32.exe, 이 실행 파일을 ODBC administrator 로 등록 합니다.

③ 위 에서 등록한 ODBC administrator 를 실행 합니다

④ 추가버튼을 클릭한 후 Adaptive Server Enterprise Driver 를 선택합니다

⑤ 해당 정보를 입력 합니다

Data source name : DB 서버를 인식할 수 있는 이름

Server Name : 접속하려고 하는 DB 서버가 있는 machine IP

Server Port : DB 서버의 listener port(개발환경 참조)

Database Name : 접속하려고 하는 Default database 이름

Logon ID : 각 개발자 login ID

모든 사항이 입력이 끝나면 advanced tab 에 있는 language 에 “us_english”를 입력합니다.

⑥ 정상적으로 설정되었는지 Test Connect 버튼을 클릭한 후 login ID 와 패스워드 입력 후 OK 버튼을 click 합니다

***** ODBC 는 가장 최신 버젼을 사용 합시다(15.0.1 PC client 에 있는 것)

Adaptive Server Enterprise15.0 Page: 79 Version: 0.1, 22 Aug 2006

Page 106: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

17.3 Interactive SQL Sybase 가 ASE 사용자를 위해 제공하는 SQL 툴로 PC client 를 설치하면 interactive SQL 이라는 폴더를 확인 할 수 있습니다. Interactive SQL 은 Java application Tool 로 T-SQL, Stored Procedure 를 개인 컴퓨터에서 데이터베이스 서버에 접속하여 실행 할 수 있는 환경을 제공할 뿐 아니라 SQL 에 대한 실행 계획은 확인 할 수 있어서 개발자 스스로가 튜닝을 쉽게 할 수 있도록 합니다. 한글 값 깨짐을 방지하기 위하여 아래 화면에서와 같이 접속 할 때 나타나는 log in 화면에서 사용자 ID, 패스워드와 함께 character set 과 language 를 맞추어 주어야 합니다(Sybase central 에 접속할 때도 마찬가지 입니다)

Character set 은 eucksc 로 Language 는 korean 으로 셋팅 하세요!!!

17.4 Plan viewer Interactive SQL 에서 실행된 Query 에 대한 Plan 을 Graphic 한 단계별 트리 구조의 형태를 나타내어 SQL 개발자 혹은 DBA 로 하여금 보다 쉽고 빠르게 단계별 Query 의 cost 를 산출하여 이를 통해 SQL 수행에 대한 정보를 체계적으로 분석할 수 있습니다.

Adaptive Server Enterprise15.0 Page: 80 Version: 0.1, 22 Aug 2006

Page 107: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

또한 Plan viewer 의 각 단계별로 보다 상세한 정보를 디스플레이 할 수 있습니다. 이러한 정보는 실제 조인절의 적절한 사용여부를 확인 할 수 있게 하므로 서 보다 정확한 SQL 문장을 구사할 수 있게 합니다.

또한 실행 Query 의 plan 을 GUI 의 트리 구조 뿐만 아니라 XML 및 일반적으로 우리가 쉽게 볼 수 있었던 Text 의 형태로도 확인할 수 있습니다

Adaptive Server Enterprise15.0 Page: 81 Version: 0.1, 22 Aug 2006

Page 108: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

18. ASE New features

18.1 12.5 에서의 변경 내용

18.1.1 외부 파일 시스템 지원

Sybase ASE 는 파일 시스템 Directory 및 Directory 기반 파일에 대한 SQL 액세스를 지원합니다. 지원하기 위한 SQL 구문은 다음과 같습니다.

create [exiting] table 테이블명

extern file at “directory_pathname” [column delimiter “delimiter”]

Directory 경로 이름은 Sybase ASE 에서 볼 수 있고 검색할 수 있는 파일 시스템 Directory 여야 합니다.

파일의 내용은 read-only 입니다.

18.1.2 뷰에서 Union 지원

이전 버전의 ASE 에서는 뷰를 정의하는 select 문의 union 연산자가 지원되지 않았지만 12.5 버전에서는 이런 제한을 없앴습니다.

18.2 12.5.0.1 에서의 변경 내용

18.2.1 insert 문을 통한 file 과 directory 생성 지원

insert 문을 통하여 file 과 directory 를 생성할 수 있습니다. 이를 위해 filename, filetype, content column 을 사용합니다. 다음과 같은 구문을 이용하여 시스템 directory 를 테이블과 같이 액세스할 수 있습니다.

Directory 를 테이블로 맵핑

create proxy_table srctab external directory at '/work/sourcedir;R’

create proxy_table dsttab external directory at '/work1/destdir;R’

Adaptive Server Enterprise15.0 Page: 82 Version: 0.1, 22 Aug 2006

Page 109: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

소스 directory 의 내용을 target directory 로 복사

insert into dsttab (filename, filetype, content) Select filename, filetype, content from srctab

18.3 12.5.0.3 에서의 변경 내용

18.3.1 len 함수

지정한 문자열 표현식의 바이트 수가 아닌 문자 수를 반환합니다. 이 때 후미 공백은 제외됩니다.

Syntax)

len(string_expression)

예)

1> select len(notes) from titles where title_id = "PC9999"

2> go

-----------

49

(1 row affected)

18.3.2 left 함수

문자열의 왼쪽 끝에서부터 지정한 수만큼의 문자를 반환합니다.

Syntax)

left(character_expression, integer_expression)

예)

1> select left(title, 5) from titles order by title_id

2> go

Adaptive Server Enterprise15.0 Page: 83 Version: 0.1, 22 Aug 2006

Page 110: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

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

The B

Cooki

You C

……….

Sushi

(18 rows affected)

18.3.3 square 함수

float 로 표현한 지정 값의 제곱근을 반환합니다.

Syntax)

square(numeric_expression)

예)

1> select square(5)

2> go

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

25.000000

(1 row affected)

18.3.4 str_replace 함수

첫 번째 문자열 표현식 내에 있는 두 번째 문자열 표현식의 인스턴스를 세 번째 표현식으로 대체합니다

Syntax)

replace("string_expression1", "string_expression2", "string_expression3")

Adaptive Server Enterprise15.0 Page: 84 Version: 0.1, 22 Aug 2006

Page 111: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

예)

1> select str_replace("cdefghi","def","yyy")

2> go

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

cyyyghi

(1 row affected)

18.3.5 year, month, day 함수

지정한 날짜의 datepart 에서 연도/월/날짜를 나타내는 정수를 반환합니다.

datepart(yy, getdate)), datepart(mm, getdate()), datepart(dd, getdate()) 와 호환됨.

Syntax)

year(date_expression)

month(date_expression)

day(date_expression)

예)

1> select year(getdate())

2> go

-----------

2006

(1 row affected)

18.3.6 newid 함수

Globally Unique ID’s (GUID) 를 반환합니다.

Syntax)

newid([optionflag])

Adaptive Server Enterprise15.0 Page: 85 Version: 0.1, 22 Aug 2006

Page 112: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

예)

1> select newid(), newid(1), newid(0x0)

2> go

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

ea7416793b7f421385f3b3f7a02a4a50 bb0da566-24ca-4d33-8125-b3f7a02a4a50 0x6c68ddfd7e2d43109f3ab3a04a502af7

(1 row affected)

18.4 12.5.1 에서의 변경 내용

18.4.1 SQL Derived Table ( Inline-View)

중첩된 select 문에서 SQL derived table 을 사용할 수 있습니다.

쿼리에서 temp table 이나 view 를 생성하지 않아도 되기 때문에 시스템 자원에 대한 overhead 가 줄며, 이를 통해 쿼리 성능이 향상됩니다.

예)

select * from (select * from table_1) derived_table_1

18.4.2 current_date, curreut_time 함수

current_date 는 현재 날짜를 date 형식으로 리턴합니다.

Current_time 은 현재 시간을 time 형식으로 리턴합니다.

예)

1> select current_date(), current_time()

2> go

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

Nov 22 2006 7:10PM

(1 row affected)

Adaptive Server Enterprise15.0 Page: 86 Version: 0.1, 22 Aug 2006

Page 113: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

18.5 12.5.3 에서의 변경 내용

18.5.1 top n 기능

top n 기능은 Microsoft SQL 서버, Adaptive Server Anywhere 및 ASIQ 와 호환됩니다.

Result set 의 rowcount 를 정수로 제한하고자 할 때 top n 절을 사용합니다.

외부 쿼리 select 문에서 top n 절을 지원하지만 서브쿼리의 select 문에서는 지원하지 않습니다. 서버쿼리에서 사용하고자 하면 구문 오류가 발생합니다.

Syntax 1 : Select)

SELECT

all_distinct_clause

TOP unsigned_integer

select_list

into_clause

from_where_clause

group_by_clause

having_clause

Syntax 2: Update)

UPDATE

TOP unsigned_integer

object_identifier

SET

set_clause_list

from_where_clause

for_clause

abstract_plan_clause

Syntax 3: Delete)

DELETE

Adaptive Server Enterprise15.0 Page: 87 Version: 0.1, 22 Aug 2006

Page 114: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

TOP unsigned_integer

result_table

from_where_clause

for_clause

abstract_plan_clause

예 1 : 일반적인 사용)

select top 5 col1 from t1

예 2 : union 과 함께 사용)

select top 2 c1 from t1

union all

select top 3 c2 from t2

18.5.2 identity 를 사용할 수 있는 type 추가

identity 로 지정할 수 있는 컬럼을 int, smallint, tinyint, numeric 으로 확장

18.6 15.0 에서의 변경 내용

18.6.1 scrollable cursor

커서의 결과 셋 안에서 커서의 위치를 패치 구문에서 next, prior, first, last, absolute, relative 등을 이용하여 자유자재로 설정할 수 있는 기능으로 커서가 오픈 되어 있는 한 결과 셋의 어떠한 데이터도 가져올 수 있거나 여러 번 검색할 수 있는 편의성을 제공합니다. Scrollable cursor 는 read only 입니다.

예)

fetch last [from] <cursor_name>

fetch absolute 500 [from] <cursor_name>

fetch {next | prior | first | last | absolute # | relative #} [from] <cursor_name>

Adaptive Server Enterprise15.0 Page: 88 Version: 0.1, 22 Aug 2006

Page 115: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

18.6.2 insensitive cursor

Insensitive cursor 는 cursor open 시 결과 set 을 worktable 에 복사합니다. 따라서 worktable 에 복사가 끝나면 소스 테이블에서 hold lock 을 해제합니다. 그리고 복사된 worktable 에서 fetch 되므로 base table 에 어떠한 데이터 변화에도 cursor 는 영향을 받지 않습니다. 따라서 insensitive cursor 는 read only cursor 입니다.

Syntax)

declare cursor_name

[semi_sensitive | insensitive] [scroll | no scroll]

cursor for select_statement

[for {read only | update [of column_name_list]}]

예)

declare stores_cur insensitive cursor for

select stor_id, stor_name

from stores where state = 'CA'

18.6.3 computed column

수식, 함수, 수 연산자, 경로명 등으로 칼럼을 생성 할 수 있는 기능으로 Computed 칼럼을 미리 검증 받아 데이터 테이블에 저장할 수도 있고 (materialized computed 칼럼), 접근 시마다 검증 받을 수도 있으며(virtual computed 칼럼) 복잡한 데이터 타입을 사용해야 할 때(데이터 타입의 결합 및 분해) 유용 합니다

예) create table rental

(cust_id int,

start_date as getdate() materialized, /* DB 에 저장된 Data 를 반환 */

today as getdate(), /* 쿼리할 때 Data 를 만들어서 반환 */

prod_id int)

인덱스는 materialized 된 computed column 에만 생성할 수 있습니다.

Adaptive Server Enterprise15.0 Page: 89 Version: 0.1, 22 Aug 2006

Page 116: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

18.6.4 function based index

인덱스 생성 시 하나 이상의 수식 또는 함수를 인덱스 키로 사용 가능한 기능으로 Computed 칼럼 과 는 다르게 데이터가 항상 미리 검증되어 인덱스 페이지에 저장되기 때문에 접근 할 때마다 검증 받을 필요가 없습니다.

예)

1>CREATE INDEX product_total ON orders (unit*price*1.1)

2>go

1>SELECT unit*price*1.1 FROM orders WHERE unit*price*1.1 > 2002

2>go

18.6.5 identity 를 사용할 수 있는 type 추가

identity 로 지정할 수 있는 컬럼을 int, smallint, tinyint, bigint, unsined bigint, unsigned smallint, numeric 으로 확장

18.6.6 Optimizer 변경

Lava Query Engine / Lava Query Execution Engine

15.0 이전 쿼리 플랜( Legacy query plan)과 새로운 쿼리 플랜 함께 사용

Optimization Goal

- allrows_oltp : OLTP 업무 (nested loop joins only, no parallelism)

- allrows_mix : Default Goal (allrows_oltp + merge joins, +parallelism)

- allrows_dss : DSS 업무 (allrows_mix + hash joins)

Syntax)

sp_configure "optimization goal", 0, “allrows_oltp"

set plan optgoal allrows_oltp

select * from A order by A.a plan "(use optgoal allrows_dss)"

18.6.7 GUI Based Plan Viewer 변경

Interactive SQL 을 이용하면 Optimizer 가 생성한 쿼리플랜을 GUI 환경으로 확인 할 수 있습니다.

Adaptive Server Enterprise15.0 Page: 90 Version: 0.1, 22 Aug 2006

Page 117: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

18.6.8 Table Partitioning

Range

Hash

Round-Robin

List

18.7 15.0.1 에서의 변경 내용

18.7.1 isdate 함수

Expression 이 날짜형식인지 확인합니다.

Syntax)

isdate(character_expression)

예)

1> select isdate("20000231"), isdate("20000228")

2> go

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

0 1

(1 row affected)

18.7.2 isnumeric 함수

Expression 이 숫자형인지 확인합니다.

Syntax)

isnumeric (character_expression)

예)

1> select isnumeric("숫자"), isnumeric("12345.67")

2> go

Adaptive Server Enterprise15.0 Page: 91 Version: 0.1, 22 Aug 2006

Page 118: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

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

0 1

(1 row affected)

Adaptive Server Enterprise15.0 Page: 92 Version: 0.1, 22 Aug 2006

Page 119: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

19. Sybase ASE 기본 Syntax

19.1 필수 Utility

19.1.1 isql 사용 방법

isql 은 command 환경에서 Sybase ASE 에 접근할 수 있도록 해주는 Utility 입니다.

Syntax)

Prompt] isql -U 사용자명 -P 사용자암호 –SDATASERVER 명

1> SQL statement

2> Go

결과 출력 ………………..

1>

19.1.2 bcp 사용 방법

bcp 는 텍스트 데이터를 Sybase ASE 에 import/export 하는 Utility 입니다.

Syntax)

Prompt] bcp DB 명..Table 명 in filename -U 사용자명 -P 암호 -c -Jiso_1

Prompt] bcp DB 명..Table 명 out filename -U 사용자명 -P 암호 -c -Jiso_1

19.2 기본 Command

19.2.1 표기법

표기 기준 예 제

1

중괄호 안에 포함된 옵션은 최소한 하나를 선택해야 합니다. 실제로 옵션을 입력할 때에는 중괄호를 사용하지 않습니다.

{cash, check, credit}

Adaptive Server Enterprise15.0 Page: 93 Version: 0.1, 22 Aug 2006

Page 120: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

2

대괄호 안에 포함된 옵션은 하나 이상을 선택하는 선택사항입니다. 실제로 옵션을 입력할 때에는 대괄호를 입력하지 않습니다.

[cash | check | credit]

3

콤마는 표시된 옵션을 원하는 만큼 선택할 수 있다는 것을 의미합니다. 선택한 옵션 사이에 콤마를 넣으십시오

cash, check, credit

4 파이프 또는 세로줄 “|” 은 표시된 옵션 중 하나만 선택할 수 있다는 것을 의미합니다.

cash | check | credit

5 생략기호(…)는 마지막 단위를 원하는 만큼 반복할 수 있다는 것을 의미합니다.

buy thing = price [cash | check | credit]

[, thing = price [cash | check | credit ]] …

19.2.2 개요

Command 설 명

alter table

테이블에 새 칼럼을 추가

제약 조건을 추가, 변경 또는 삭제

기존 테이블을 partition 또는 unpartition 함

begin … end if … else 와 같은 흐름 제어 구문이 동일한 범위에 영향을 미치도록 SQL 구문을 묶습니다.

begin transaction 사용자 정의 트랜잭션의 시작 위치를 표시합니다.

break while 루프를 종료합니다. break 문은 주로 if 문과 함께 사용됩니다.

case SQL 표현식에 조건부 값을 사용할 수 있도록 합니다.

close 커서를 비활성화합니다.

commit 사용자 정의 트랜잭션의 종료 위치를 표시합니다.

continue while 루프를 재시작합니다. 주로 if 문과 함께 사용됩니다.

create index 테이블에 인덱스를 생성합니다.

create procedure Stored procedure 를 생성합니다.

Adaptive Server Enterprise15.0 Page: 94 Version: 0.1, 22 Aug 2006

Page 121: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

create table 테이블을 생성합니다.

create trigger 트리거를 생성합니다.

create view 뷰를 생성합니다.

deallocate cursor 커서를 액세스할 수 없도록 만들고 이 커서로 생성된 모든 메모리 리소스를 해제합니다.

declare 로컬 변수 선언

declare cursor 커서를 정의합니다.

delete 테이블에서 데이터 행 삭제

drop index 인덱스를 삭제합니다.

drop procedure Stored Procedure 를 삭제합니다.

drop table 테이블 정의 및 관련 정보를 삭제합니다.

drop trigger 트리거를 삭제합니다.

drop view 뷰를 삭제합니다.

execute Stored Procedure 또는 동적 SQL 을 실행합니다.

fetch 커서 결과 set 을 return 합니다.

goto Label Label 으로 분기합니다.

if … else SQL 구문 실행에 조건을 부과합니다.

insert 테이블이나 뷰에 새 행을 추가합니다.

open 처리를 위해 커서를 엽니다.

raiserror 사용자 정의 에러 메시지를 사용자 화면에 출력하고 시스템 플래그를 설정하여 에러 상태가 발생하였음을 기록합니다.

return 일괄 처리 또는 Stored Procedure 에서 무조건 종료하며, return 상태 코드를 제공하는 옵션이 있습니다. return 다음에 오는 구문은 실행되지 않습니다.

rollback 트랜잭션 내의 마지막 savepoint 나 트랜잭션의 시작으로 사용자 정의 트랜잭션을 롤백합니다.

select 데이터베이스 객체에서 행을 검색합니다.

set 세션 처리 옵션을 설정합니다.

truncate table 테이블에서 모든 행을 삭제합니다.

union 연산자 둘 이상의 쿼리 결과를 결합하여 하나의 결과 set 을 return 합니다.

Adaptive Server Enterprise15.0 Page: 95 Version: 0.1, 22 Aug 2006

Page 122: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

update 데이터를 추가하거나 변경합니다.

while 구문 또는 구문 블록의 반복 실행 조건을 설정합니다.

19.2.3 alter table

테이블에 새 칼럼을 추가

제약 조건을 추가, 변경 또는 삭제

기존 테이블을 partition 또는 unpartition 함

alter table [[database.][owner].table_name

{ add column_name datatype}

[default {constant_expression | user | null}]

{identity | null | not null}

[off row | in row]

[ [constraint constraint_name]

{ { unique | primary key }

[clustered | nonclustered]

[asc | desc]

[with { fillfactor = pct,

max_rows_per_page = num_rows,

reservepagegap = num_pages }]

[on segment_name]

| references [[database.]owner.]ref_table

[(ref_column)]

[match full]

| check (search_condition) ] ... }

[, next_column]...

| add {[constraint constraint_name]

{ unique | primary key}

[clustered | nonclustered]

(column_name [asc | desc][, column_name [asc | desc]...])

Adaptive Server Enterprise15.0 Page: 96 Version: 0.1, 22 Aug 2006

Page 123: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

[with { fillfactor = pct,

max_rows_per_page = num_rows,

reservepagegap = num_pages}]

[on segment_name]

| foreign key (column_name [{, column_name}...])

references [[database.]owner.]ref_table

[(ref_column [{, ref_column}...])]

[match full]

| check (search_condition)}

| drop {column_name [, column_name]...

| constraint constraint_name }

| modify column_name datatype [null | not null]

[, next_column]...

| replace column_name

default { constant_expression | user | null}

| { enable | disable } trigger

| lock {allpages | datarows | datapages } }

| with exp_row_size=num_bytes

| partition number_of_partitions

| unpartition

| partition_clause

| add_partition_clause

19.2.4 begin … end

if … else 와 같은 흐름 제어 구문이 동일한 범위에 영향을 미치도록 SQL 구문을 묶습니다.

begin

statement block

end

Adaptive Server Enterprise15.0 Page: 97 Version: 0.1, 22 Aug 2006

Page 124: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

예)

if (select avg(price) from titles) < $15

begin

update titles

set price = price * $2

select title, price

from titles

where price > $28

end

else

print "we don't need query!"

19.2.5 begin transaction

사용자 정의 트랜잭션의 시작 위치를 표시합니다.

begin tran[saction] [transaction_name]

예)

begin transaction

insert into publishers (pub_id) values ("9999")

commit transaction

19.2.6 break

while 루프를 종료합니다. Break 문은 주로 if 문과 함께 사용됩니다.

while logical_expression

statement

break

statement

Adaptive Server Enterprise15.0 Page: 98 Version: 0.1, 22 Aug 2006

Page 125: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

continue

예)

while (select avg(price) from titles) < $30

begin

update titles

set price = price * 2

select max(price) from titles

if (select max(price) from titles) > $50

break

else

continue

end

19.2.7 case

SQL 표현식에 조건부 값을 사용할 수 있도록 합니다.

case

when search_condition then expression

[when search_condition then expression]...

[else expression]

end

case expression

when expression then expression

[when expression then expression]...

[else expression]

end

예)

select au_lname, postalcode,

case

Adaptive Server Enterprise15.0 Page: 99 Version: 0.1, 22 Aug 2006

Page 126: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

when postalcode = "94705" then "Berkeley Author"

when postalcode = "94609" then "Oakland Author"

when postalcode = "94612" then "Oakland Author"

when postalcode = "97330" then "Corvallis Author"

else "Not exists"

end

from authors

19.2.8 close

커서를 비활성화합니다.

close cursor 명

예)

close author_cur

19.2.9 commit

사용자 정의 트랜잭션의 종료 위치를 표시합니다.

commit [tran | transaction | work] [transaction_name]

예)

begin transaction royalty_change

update titleauthor

set royaltyper = 65 from titleauthor, titles

where royaltyper = 75

and titleauthor.title_id = titles.title_id

and title = "The Gourmet Microwave"

Adaptive Server Enterprise15.0 Page: 100 Version: 0.1, 22 Aug 2006

Page 127: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

update titleauthor

set royaltyper = 35 from titleauthor, titles

where royaltyper = 25

and titleauthor.title_id = titles.title_id

and title = "The Gourmet Microwave"

save transaction percentchanged

update titles

set price = price * 1.1

where title = "The Gourmet Microwave"

select (price * total_sales) * royaltyper

from titles, titleauthor

where title = "The Gourmet Microwave"

and titles.title_id = titleauthor.title_id

rollback transaction percentchanged

commit transaction

19.2.10 continue

while 루프를 재시작합니다. 주로 if 문과 함께 사용됩니다.

while logical_expression

statement

break

statement

continue

예)

while (select avg(price) from titles) < $30

begin

update titles

set price = price * 2

Adaptive Server Enterprise15.0 Page: 101 Version: 0.1, 22 Aug 2006

Page 128: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

select max(price) from titles

if (select max(price) from titles) > $50

break

else

continue

end

19.2.11 create index

테이블에 인덱스를 생성합니다.

General Syntax :

create [unique] [clustered | nonclustered] index index_name

on [[database.]owner.]table_name

(column_expression [asc | desc]

[, column_expression [asc | desc]]...)

[with { fillfactor = pct,

max_rows_per_page = num_rows,

reservepagegap = num_pages,

consumers = x, ignore_dup_key, sorted_data,

[ignore_dup_row | allow_dup_row],

statistics using num_steps values } ]

[on segment_name]

[ index_partition_clause ]

Function Based Index Syntax :

create [unique | nonclustered] index index_name

on [[ database.] owner.] table_name

(column_expression [asc | desc]

[, column_expression [asc | desc]]...

Adaptive Server Enterprise15.0 Page: 102 Version: 0.1, 22 Aug 2006

Page 129: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

19.2.12 create procedure

Stored Procedure 를 생성합니다.

create procedure [owner.]procedure_name[;number]

[[(]@parameter_name

datatype [(length ) | (precision [, scale ])]

[= default][output]

[, @parameter_name

datatype [(length ) | (precision [, scale ])]

[= default][output]]...[)]]

[with recompile]

as {SQL_statements | external name dll_name}

19.2.13 create table

테이블을 생성합니다.

create table [database .[owner ].]table_name (column_name datatype

[default {constant_expression | user | null}]

{[{identity | null | not null}]

[off row | [ in row [ (size_in_bytes) ] ]

[[constraint constraint_name ]

{{unique | primary key}

[clustered | nonclustered] [asc | desc]

[with { fillfactor = pct,

max_rows_per_page = num_rows, }

reservepagegap = num_pages }]

[on segment_name]

| references [[database .]owner .]ref_table

[(ref_column )]

[match full]

| check (search_condition)}]}

Adaptive Server Enterprise15.0 Page: 103 Version: 0.1, 22 Aug 2006

Page 130: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

[match full]...

| [constraint constraint_name]

{{unique | primary key}

[clustered | nonclustered]

(column_name [asc | desc]

[{, column_name [asc | desc]}...])

[with { fillfactor = pct

max_rows_per_page = num_rows ,

reservepagegap = num_pages } ]

[on segment_name]

|foreign key (column_name [{,column_name}...])

references [[database.]owner.]ref_table

[(ref_column [{, ref_column}...])]

[match full]

| check (search_condition) ... }

[{, {next_column | next_constraint}}...])

[lock {datarows | datapages | allpages }]

[with { max_rows_per_page = num_rows,

exp_row_size = num_bytes,

reservepagegap = num_pages,

identity_gap = value } ]

[on segment_name ]

[ partition_clause ]

[ [ external table ] at pathname ]

19.2.14 create trigger

트리거를 생성합니다.

create trigger [owner .]trigger_name

on [owner .]table_name

for {insert , update , delete}

Adaptive Server Enterprise15.0 Page: 104 Version: 0.1, 22 Aug 2006

Page 131: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

as

SQL_statements

Or, 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 ]...

19.2.15 create view

뷰를 생성합니다.

create view [owner .]view_name

[(column_name [, column_name ]...)]

as

select [distinct] select_statement

[with check option]

19.2.16 deallocate cursor

커서를 액세스할 수 없도록 만들고 이 커서로 생성된 모든 메모리 리소스를 해제해야 합니다.

deallocate [cursor] cursor 명

Adaptive Server Enterprise15.0 Page: 105 Version: 0.1, 22 Aug 2006

Page 132: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

예)

deallocate cursor author_cur

19.2.17 declare

로컬 변수 선언

declare @variable_name datatype

[, @variable_name datatype]...

예)

Declare @var1 char(10), @var2 int

19.2.18 declare cursor

커서를 선언 합니다.

declare cursor_name

[semi_sensitive | insensitive] [scroll | no scroll]

cursor for select_statement

[for {read only | update [of column_name_list]}]

*** 일반적인 조회 작업시는 insensitive cursor 를 사용할 것

예)

declare stores_cur insensitive cursor for

select stor_id, stor_name

from stores where state = 'CA'

Adaptive Server Enterprise15.0 Page: 106 Version: 0.1, 22 Aug 2006

Page 133: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

19.2.19 delete

테이블에서 데이터 행을 삭제합니다.

delete

[top unsigned_integer]

[from] [[database.]owner.]{view_name|table_name}

[where search_conditions]

[plan "abstract plan"]

delete [[database.]owner.]{table_name | view_name}

[from [[database.]owner.]{view_name [readpast]|

table_name [readpast]

[(index {index_name | table_name }

[ prefetch size ][lru|mru])]}

[, [[database.]owner.]{view_name [readpast]|

table_name [readpast]

[(index {index_name | table_name }

[ prefetch size ][lru|mru])]} ...]

[where search_conditions] ]

[plan "abstract plan"]

delete [from] [[database.]owner.]{table_name|view_name}

where current of cursor_name

예)

delete titles

from titles, authors, titleauthor

where authors.au_lname = 'Bennet'

and authors.au_id = titleauthor.au_id

and titleauthor.title_id = titles.title_id

Adaptive Server Enterprise15.0 Page: 107 Version: 0.1, 22 Aug 2006

Page 134: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

19.2.20 drop index

인덱스를 삭제합니다.

drop index table_name.index_name

[, table_name.index_name] ...

예)

drop index authors.au_id_ind

19.2.21 drop procedure

Stored Procedure 를 삭제합니다.

drop proc[edure] [owner.]procedure_name

[, [owner.]procedure_name] ...

예)

drop procedure usp_myproc

19.2.22 drop table

테이블 정의 및 관련 정보를 삭제합니다.

drop table [[database.]owner.]table_name

[, [[database.]owner.]table_name ] ...

예)

drop table roysched

Adaptive Server Enterprise15.0 Page: 108 Version: 0.1, 22 Aug 2006

Page 135: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

19.2.23 drop trigger

트리거를 삭제합니다.

drop trigger [owner.]trigger_name

[, [owner.]trigger_name] ...

예)

drop trigger myTrigger1

19.2.24 drop view

뷰를 삭제합니다.

drop view [owner.]view_name [, [owner.]view_name] ...

예)

drop view new_price

19.2.25 execute

Stored Procedure 또는 동적 SQL 을 실행합니다.

Stored Procedure 실행 Syntax :

[exec[ute]] [@return_status = ]

[[[server .]database.]owner.]procedure_name[;number]

[[@parameter_name =] value |

[@parameter_name =] @variable [output]

[,[@parameter_name =] value |

[@parameter_name =] @variable [output]...]]

[with recompile]

Adaptive Server Enterprise15.0 Page: 109 Version: 0.1, 22 Aug 2006

Page 136: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

Dynamic SQL 실행 Syntax :

exec[ute] ("string" | char_variable

[+ "string" | char_variable]...)

예 1 : Stored Procedure 호출)

declare @percent int

select @percent = 10

execute roy_check "BU1032", 1050, @pc = @percent output

select Percent = @percent

예 2 : Dynamic SQL 실행)

declare @tablename char(20)

declare @columname char(20)

select @tablename="sysobjects”

select @columname="name"

execute ('select ' + @columname + ' from ' + @tablename + ' where id=3')

19.2.26 fetch

커서 결과 set 을 return 합니다.

fetch [next |prior | first | last | absolute

fetch_offset | relative fetch_offset ]

[ from ] cursor_name

[ into fetch_target_list ]

예)

fetch pubs_crsr into @name, @city, @state

Adaptive Server Enterprise15.0 Page: 110 Version: 0.1, 22 Aug 2006

Page 137: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

19.2.27 goto Label

Label 으로 분기합니다.

label:

goto label

예)

declare @count smallint

select @count = 1

restart:

print "yes"

select @count = @count + 1

while @count <=4

goto restart

19.2.28 if …. else

SQL 구문 실행에 조건을 부과합니다.

if logical_expression [plan "abstract plan"]

statements

[else

[if logical_expression] [plan "abstract plan"]

statement]

예)

if (select max(id) from sysobjects) < 100

print "No user-created objects in this database"

Adaptive Server Enterprise15.0 Page: 111 Version: 0.1, 22 Aug 2006

Page 138: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

else

begin

print "These are the user-created objects"

select name, type, id

from sysobjects

where id > 100

end

19.2.29 insert

테이블이나 뷰에 새 행을 추가합니다.

insert [into] [database.[owner.]]{table_name|view_name}

[(column_list)]

{values (expression [, expression]...)

|select_statement [plan "abstract plan"] }

예)

insert titles

values("BU2222", "Faster!", "business", "1389",

null, null, null, "ok", "06/17/87", 0)

insert newauthors

select * from authors where city = "San Francisco"

19.2.30 open

처리를 위해 커서를 엽니다.

open cursor 명

예)

open author_cur

Adaptive Server Enterprise15.0 Page: 112 Version: 0.1, 22 Aug 2006

Page 139: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

19.2.31 raiserror

사용자 정의 에러 메시지를 사용자 화면에 출력하고 시스템 플래그를 설정하여 에러 상태가 발생하였음을 기록합니다.

raiserror error_number

[{format_string | @local_variable}] [, arg_list]

[with errordata restricted_select_list]

예)

create procedure usp_showtable @tabname varchar(18)

as

if not exists (select name from sysobjects

where name = @tabname)

begin

raiserror 99999 "Table %1! not found.", @tabname

end

else

begin

select sysobjects.name, type, crdate, indid

from sysindexes, sysobjects

where sysobjects.name = @tabname

and sysobjects.id = sysindexes.id

end

19.2.32 return

일괄 처리 또는 Stored Procedure 에서 무조건 종료하며, return 상태 코드를 제공하는 옵션이 있습니다. return 다음에 오는 구문은 실행되지 않습니다.

Adaptive Server Enterprise15.0 Page: 113 Version: 0.1, 22 Aug 2006

Page 140: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

return [integer_expression] [plan "abstract plan"]

예 1 : return 처리)

create proc usp_myproc @param varchar(11)

as

declare @status int

if (select contract from titles where title_id = @param)= 1

return 1

else

return 2

예 2 : return value 처리)

delcare @retval int

execute @retval = usp_myproc

19.2.33 rollback

트랜잭션 내의 마지막 savepoint 나 트랜잭션의 시작으로 사용자 정의 트랜잭션을 롤백합니다.

rollback [tran | transaction | work]

[transaction_name | savepoint_name]

예)

begin transaction

delete from publishers where pub_id = "9906"

rollback transaction

Adaptive Server Enterprise15.0 Page: 114 Version: 0.1, 22 Aug 2006

Page 141: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

19.2.34 select

select [ all | distinct ]

[top unsigned_integer]

select_list

[into_clause ]

[from_clause ]

[where_clause ]

[group_by_clause]

[having_clause ]

[order_by_clause ]

[compute_clause ]

[read_only_clause ]

[isolation_clause ]

[browse_clause ]

[plan_clause ]

19.2.35 set set ansinull {on | off}

ansinull : 집계함수(Aggregate function)에서 NULL 값인 피연산자의 값이 SQL92 표준과 호환될지 여부 결정

set {chained, close on endtran, nocount, noexec, parseonly, showplan } {on | off}

chained : chained 모드로 트랜잭션 처리

close on endtran : 트랜잭션이 종료되면 트랜잭션 내의 모든 커서 닫음

nocount: 구문의 영향을 받는 행의 표시 제어

noexec : 각 쿼리를 컴파일하지만 실행하지는 않음

parseonly : 각 쿼리의 구문을 검사한 다음 컴파일하거나 실행하지 않고

오류메시지 리턴

showplan : 쿼리 처리를 위한 옵티마이저의 쿼리 플랜을 생성

set [clientname client_name | clienthostname host_name

Adaptive Server Enterprise15.0 Page: 115 Version: 0.1, 22 Aug 2006

Page 142: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

| clientapplname application_name]

clientappname : 응용 프로그램에 개별 이름 할당

clienthostname : 호스트에 개별 이름 할당

clientname : 클라이언트에 개별 이름 할당

set cursor rows number for cursor_name

cursor rows : 커서 fetch 시 요청에 대해 number 만큼의 행을 return

set forceplan {on | off}

쿼리 옵티마이저가 쿼리의 from 절에 있는 테이블의 순서를 쿼리 계획의 조인순서로 사용하도록 합니다.

set plan optgoal allrows_mix | allrows_dss | allrows_oltp

쿼리 옵티마이저가 업무(OLTP, DSS, MIX)에 맞는 쿼리 플랜을 생성하도록 한다.

set quoted_identifier {on | off}

on 으로 설정될 경우 큰 따옴표에 포함된 모든 문자열은 식별자로 처리됩니다.

set {rowcount number, textsize number}

rowcount : 지정된 행이 처리된 후 진행을 멈춥니다.

set rowcount 0 으로 이 옵션을 해제할 수 있습니다.

set statistics {io, time} {on | off}

io : SQL 구문에서 참조하는 논리적 읽기, 물리적 읽기, 테이블 액세스 횟수등의 통계 정보를 표시합니다.

time : SQL 구문을 분석하고 컴파일하는데 소요한 시간을 표시합니다.

set string_rtruncation {on | off}

insert 또는 update 명령이 문자열을 truncation 할 때 예외를 발생할 지 여부를 지정합니다.

Adaptive Server Enterprise15.0 Page: 116 Version: 0.1, 22 Aug 2006

Page 143: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

set transaction isolation level {

[ read uncommitted | 0 ] |

[ read committed | 1 ] |

[ repeatable read | 2 ] |

[ serializable | 3 ] }

세션에 대한 트랜잭션 isolation level 을 설정합니다.

19.2.36 truncate table truncate table [ [ database.]owner.]table_name

[ partition partition_name ]

예)

truncate table mytable

19.2.37 unoin 연산자

select [top unsigned_integer] select_list

[into clause]

[from clause] [where clause]

[group by clause] [having clause]

[union [all]

select [top unsigned_integer] select_list

[from clause] [where clause]

[group by clause] [having clause] ]...

[order by clause]

[compute clause]

Adaptive Server Enterprise15.0 Page: 117 Version: 0.1, 22 Aug 2006

Page 144: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

19.2.38 update

update [top unsigned_integer]

[[database.]owner.]{table_name | view_name}

set [[[database.]owner.]{table_name.|view_name.}]

column_name1 =

{expression1 | NULL | (select_statement)} |

variable_name1 =

{expression1 | NULL | (select_statement)}

[, column_name2 =

{expression2 | NULL | (select_statement)}]... |

[, variable_name2 =

{expression2 | NULL | (select_statement)}]...

[from [[database.]owner.]{view_name [readpast]|

table_name [readpast]

[(index {index_name | table_name}

[ prefetch size ][lru|mru])]}

[,[[database.]owner.]{view_name [readpast]|

table_name [readpast]

[(index {index_name | table_name }

[ prefetch size ][lru|mru])]}]

...]

[where search_conditions]

[plan "abstract plan"]

update [[database.]owner.]{table_name | view_name}

set [[[database.]owner.]{table_name.|view_name.}]

column_name1 =

{expression1 | NULL | (select_statement)} |

variable_name1 =

{expression1 | NULL | (select_statement)}

[, column_name2 =

{expression2 | NULL | (select_statement)}]... |

Adaptive Server Enterprise15.0 Page: 118 Version: 0.1, 22 Aug 2006

Page 145: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

[, variable_name2 =

{expression2 | NULL | (select_statement)}]...

where current of cursor_name

19.2.39 while

while logical_expression [plan "abstract plan"]

statement

예)

while (select avg(price) from titles) < $30

begin

select title_id, price from titles

where price > $20

update titles

set price = price * 2

end

Adaptive Server Enterprise15.0 Page: 119 Version: 0.1, 22 Aug 2006

Page 146: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

19.3 기본 Built-in Function

19.3.1 개요

함 수 명 유 형 리턴값 적용버전

abs 수학 표현식의 절대값

ascii 문자열 표현식의 첫 문자에 대한 ASCII 코드

avg 집계 모든 고유 값의 산술 평균

ceiling 수학 지정된 값보다 크거나 같은 최소 정수

char 문자열 정수와 대등한 문자

charindex 문자열 표현식의 시작 위치를 나타내는 정수를 반환합니다.

char_length 문자열 표현식의 문자 수

col_length 시스템 정의된 열의 길이

convert 데이터 유형변환

다른 데이터 유형 또는 datetime 표시 형식으로 변환된 지정 값

count 집계 null 이 아닌 고유한 값의 수

current_date 날짜 현재 날짜를 반환합니다. 12.5.1

current_time 날짜 현재 시간을 반환합니다. 12.5.1

datalength 시스템 지정된 열 또는 문자열의 실제 바이트 단위 길이

dateadd 날짜 주어진 년도, 분기, 시간 또는 기타 날짜 부분을 지정된 날짜에 더하여 만든 날짜

datediff 날짜 두 날짜 표현식 간의 차이

datename 날짜 날짜 표현식에서 지정된 부분의 이름

datepart 날짜 날짜 표현식에서 지정된 부분의 정수 값

day 날짜 지정한 날짜의 datepart 에서 날짜를 나타내는 정수를 반환합니다.

12.5.0.3

floor 수학 지정된 값보다 작거나 같은 최대 정수

getdate 날짜 시스템의 현재 날짜 및 시간

hextoint 데이터 지정된 16 진수 문자열에 해당하는

Adaptive Server Enterprise15.0 Page: 120 Version: 0.1, 22 Aug 2006

Page 147: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

유형변환 플랫폼 독립 정수

isdate 시스템 Expression 이 날짜형식인지 확인합니다. 15.0.1

isnull 시스템 expression1 이 NULL 로 계산되는 경우 expression2 에 지정된 값으로 대체합니다.

isnumeric 시스템 Expression 이 숫자형인지 확인합니다. 15.0.1

ltrim 문자열 선두 공백이 제거된 지정 표현식

left 문자열 문자열의 왼쪽 끝에서부터 지정한 수만큼의 문자를 반환합니다.

12.5.0.3

len 문자열 지정한 문자열 표현식의 바이트 수가 아닌 문자 수를 반환합니다. 이 때 후미 공백은 제외됩니다.

12.5.0.3

max 집계 열의 최고 값

min 집계 열의 최하 값

month 날짜 지정한 날짜의 datepart 에서 월을 나타내는 정수를 반환합니다.

12.5.0.3

newid 시스템 Globally Unique ID’s (GUID) 반환 12.5.0.3

patindex 문자열 텍스트 및 이미지 지정된 패턴이 처음 발생한 시작 위치

pi 수학 상수 값 3.1415926535897936

power 수학 지정된 숫자를 주어진 거듭제곱으로 증가시키는 경우 결과 값

radians 수학 지정된 각도의 라디안 단위 각도 크기

rand 수학 지정된 시드 값을 사용하여 생성된 0 과 1 사이의 임의 값

replicate 문자열 지정된 횟수만큼 반복되는 표현식으로 구성되는 문자열

reverse 문자열 역순으로 열거된 문자의 지정 문자열

right 문자열 오른쪽에서 지정된 수의 문자를 시작하는 문자 표현식의 일부

round 수학 주어진 소수점 자리로 반올림된 지정된 숫자의 값

Adaptive Server Enterprise15.0 Page: 121 Version: 0.1, 22 Aug 2006

Page 148: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

rtrim 문자열 후미 공백이 제거된 지정 표현식

space 문자열 지정된 수의 단일 바이트 공간으로 구성되는 문자열

square 수학 float 로 표현한 지정 값의 제곱근을 반환합니다.

12.5.0.3

sqrt 수학 지정된 숫자의 제곱근

str 문자열 지정된 숫자와 대등한 문자

str_replace 문자열 첫 번째 문자열 표현식 내에 있는 두 번째 문자열 표현식의 인스턴스를 세 번째 표현식으로 대체합니다.

12.5.0.3

stuff 문자열 특정 문자열에서 지정된 수의 문자를 삭제하고 다른 문자열로 바꾸어 만들어진 문자열

substring 문자열 다른 문자열에서 지정된 수의 문자를 추출하여 만들어진 문자열

sum 집계 값 총계

upper 문자열 지정된 문자열과 대등한 대문자

year 날짜 지정한 날짜의 datepart 에서 연도를 나타내는 정수를 반환합니다.

12.5.0.3

19.3.2 사용법

select abs(-1)

select ascii("a")

select avg(advance), sum(total_sales) from titles where type = "business"

select ceiling(123.45)

select char(42)

select charindex("der", "wonderful")

select char_length(notes) from titles where title_id = "PC9999"

select convert(integer, 0x00000100)

select convert(varchar, getdate(), 23)

Adaptive Server Enterprise15.0 Page: 122 Version: 0.1, 22 Aug 2006

Page 149: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

표 1) 년도를 char 또는 varchar 로 변경할 때 사용되는 옵션값 년도 2 자리 년도 4 자리 형식

- 또는 0 100 Default

mon dd yyyy, hh:mm AM (or PM)

1 101 USA mm/dd/yy

2 102 SQL standard yy.mm.dd

3 103 English/French dd/mm/yy

4 104 German dd.mm.yy

5 105 dd-mm-yy

6 106 dd mon yy

7 107 mon dd, yy

8 108 HH:mm:ss

- 또는 9 109 Default + milliseconds mon dd yyyy hh:mm:sss AM (or PM)

10 110 USA mm-dd-yy

11 111 Japan yy/mm/dd

12 112 yymmdd

13 113 yy/dd/mm

14 114 mm/yy/dd

15 115 dd/yy/mm

16 116 mon dd yy HH:mm:ss

17 NONE hh:mmAM

18 NONE HH:mm

19 NONE hh:mm:ss:zzzAM

20 NONE hh:mm:ss:zzz

21 NONE yy/mm/dd

22 NONE yy/mm/dd

23 NONE yyyy-mm-ddTHH:mm:ss

select current_date()

select current_time()

Adaptive Server Enterprise15.0 Page: 123 Version: 0.1, 22 Aug 2006

Page 150: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

select datalength(col1) from table1

select dateadd(hh, 24, "4/1/1979")

select datediff(yy, convert(date, "4/1/1999"), convert(date, "4/1/2000"))

year : yy

quater : qq

week : wk

day : dd

dayofyear : dy

weekday : dw

hour : hh

minute : mi

second : ss

millisecond : ms

select datename(mm, getdate())

select datepart(month, getdate())

select day(getdate())

select floor(123.45)

select getdate()

select hextoint ("0x00000100")

select isdate("20001231")

select isnull(price,0) from titles

select isnumeric("12345")

select ltrim(" aaa")

select left("abc", 1)

select len("abcdefg")

select max(discount) from salesdetail

select min(discount) from salesdetail

select newid(), newid(1), newid(0x0)

select au_id, patindex("%circus%", copy) from blurbs

select pi()

select power(2, 3)

Adaptive Server Enterprise15.0 Page: 124 Version: 0.1, 22 Aug 2006

Page 151: ASE Programming Guide for Oracle programmers ·  · 2007-04-18프로그램 개발자 가이드 Sybase Presales 7.2 데이터 타입 선언.....8 7.2.1 테이블의 열에 대한

프로그램 개발자 가이드 Sybase Presales

select radians(2578)

select rand()

select replicate("abcd", 3)

select reverse("abcde")

select right("abcde", 3)

select round(123.4545, 2)

select rtrim("aaa ")

select "aaa" + space(5) + "bbb"

select square(5)

select sqrt(25)

select str(12345.1234, 10, 4)

select str_replace("cdefghi","def","yyy")

select stuff("abc", 2, 3, "xyz")

select au_lname, substring(au_fname, 1, 1) from authors

select avg(advance), sum(total_sales) from titles where type = "business"

select upper("abcd")

year("11/02/03")

Adaptive Server Enterprise15.0 Page: 125 Version: 0.1, 22 Aug 2006