티스토리 툴바

Scrollable Cursor

ASE Certification 준비 2009/07/08 18:20 posted by 클리어리

Q. Which of the following are true about cursors? (Choose 2)
   1) the default behavior for cursors is scrollable
   2) scrollable cursors are always read only
   3) scrollable cursors may only update one table at a time
   4) the default behavior for cursors is non-scrollable
   5) only one scrollable cursor can be used on a server at a time

A : 2), 4)

※ default cursor : semi-sensitive, non-scrollable
    (아무 function 없이 declare 만 했을 경우 가지는 default 속성)

※ All scrollable cursors are read-only.
   (모든 scrollable cursors는 read-only 속성을 갖음)

※ Any cursor that can be updated is non-scrollable.
   (for update mode으로 선언된 cursor는 모두 non-scrollable 속성을 갖음)



※ Cursor

select 문으로 긁은 data를 담은 것으로 두 개의 부분(part)으로 이루어져 있다.

1. Cursor result set  : select문으로 긁은 data set (table)
2. Cursor position : 위의 결과 set 의 한 row에 대한 포인터
                            ( a pointer to a row within the cursor result set )


Cursor의 동작(cursor’s behavior)에 따른 두 가지 속성

1. sensitivity : base table 의 data변경에 영향을 받는지 안 받는지의 여부

   1.1. insensitive
        - cursor가 open된 이후에 base table(cursor를 선언했을 때 select문에 사용되어진 table)의 
          data가 변경되더라도 cursor의 result set에는 영향이 없다.

   1.2. semi-sensitive (default)
        - cursor가 open된 이후에 base table의 data가 변경되면 cursor result set에 반영이 될 수도
          있고 안 될 수도 있다. (참... 무책임하다..ㅡ.,ㅡ)
          ( If you declare it semi_sensitive, some changes in the base tables
            made since opening the cursor may appear in the result set. Data changes
            may or may not be visible to the semi-sensitive cursor. )


2. scrollability : 순차적으로 fetch를 할 수 있느냐 없느냐의 여부

   2.1. scroll 

       - ASE 15.0 부터 지원되는 기능

       - 모든 scrollable cursors는 read-only 속성을 갖음

       - 기존 버전에서는 fetch가 순차적으로만, 또 한번 fetch된 row는 재 fetch를 못했던 것과 달리
         순차적 뿐 만 아니라. 자신이 원하는 행의 row를 바로 fetch할 수 있고  한 번 fetch된 rows를 
         반복해서 fetch할 수도 있음. 또한, 역순서로도 fetch할 수 있는 기능 제공 함.

       - 동시에 한 row 이상 fetch된 cursor result set 을 검색, 이동할 수 있다.

        (  “Scrollable” means that you can scroll through the cursor result set by fetching
           any, or many, rows, rather than one row at a time; you can also scan the result
           set repeatedly.

           A scrollable cursor allows you to set the position of the cursor
           anywhere in the cursor result set for as long as the cursor is open, by specifying
           the option first, last, absolute, next, prior, or relative in a fetch statement.  )

ex)
       fetch last [from] <cursor_name>
       fetch absolute 500 [from] <cursor_name>


   2.2. no scroll (default)

       - 기존 버전과 다를 바 없음. 순차적으로만 fetch 가능.

       - for update mode으로 선언된 cursor는 모두 non-scrollable.



read-only mode으로 선언된 cursor는 where절에 쓸 수 없지만,
    update mode으로 선언된 cursor는 where절에 쓸 수 있다.

[read-only mode 의 Example]

-- 1. cursor 선언
  declare types_insert cursor
  for select distinct type from titles
  for read only
  go

  declare @type char(12),
             @avg_price money

-- 2. cursor open
  open types_insert

-- 3. fetch
  fetch types_insert into @type

  while @@sqlstatus = 0
  begin
  select @avg_price = avg(price) from titles where type = @type
  insert into types values (@type, @avg_price)
  fetch types_insert into @type
  end

-- 4. cursor close (close된 cursor는 deallocate되지 않는 한 재 open 할 수 있음.)
  close types_insert

-- 5. cursor deallocate (메모리로부터 완전 제거, 재 open 할 수 없음.)
  deallocate cursor types_insert

  select * from types
  go


[update mode 의 Example]
--> Declare cursor.
--> Declare variables.
--> Open cursor.


declare price_update cursor
for select title, price, total_sales from titles
for update
go

declare @avg_sales    int,
           @avg_price     money,
           @title              varchar(80),
           @price            money,
           @total_sales    int

open price_update

begin tran
select @avg_sales = avg(total_sales),
         @avg_price  = avg(price)
from    titles holdlock

--> Fetch the first row into the target list.
fetch price_update into @title, @price, @total_sales

--> Start a while loop that executes if there are more rows to fetch.

begin /* of while loop */
--> Check for a fetch error. If one occurred,
-- roll back the transaction, send an error
-- message to the user, close and deallocate
-- the cursor and exit the batch.

while @@sqlstatus <> 2
if @total_sales > @avg_sales and @price < @avg_price
begin
--> Increase the price in the titles table by 10%.
update titles
set price = price * $1.10
where current of price_update
if @@error <> 0
begin
rollback tran

raiserror 22001 "Update failed"

--> Close and deallocate cursor.
close price_update
deallocate cursor price_update
end
else
print "Increased price of %1! by 10 percent.", @title
end
else if @total_sales < @avg_sales and @price > @avg_price
begin
update titles
set price = price * $0.80
where current of price_update
if @@error <> 0
begin
rollback tran
raiserror 22001 "Update failed"

--> Close and deallocate cursor.
close price_update
deallocate cursor price_update
end
else
print "Decreased price of %1! by 20 percent.", @title
end
fetch price_update into @title, @price, @total_sales
end /* end of while loop */
if @@sqlstatus = 1
begin
rollback tran

raiserror 21001 "Fetch failed in cursor."
close price_update
deallocate cursor price_update
return
end

commit tran

--> Close and deallocate cursor.
close price_update
deallocate cursor price_update
go

'ASE Certification 준비' 카테고리의 다른 글

Scrollable Cursor  (0) 2009/07/08
partition에 관한 문제  (0) 2009/07/01
grant 에 관한 문제  (0) 2009/07/01

DB copy 방법

ASE 2009/07/07 18:28 posted by 클리어리
1. 스키마만 복제를 원할 경우

ddlgen
-Ulogin_name -Ppasswd -Shostname:port number -TDB -Ddatabase_name -Ofile_name

명령프롬프트에서 위와 같이 명령을 하면 스키마 스크립트를 얻을 수 있다.

같은 서버에 복제할 경우 스크립트에서 DB명을 포함 몇 가지 수정할 것 수정해서 바로 실행해주면 되고

스키마 뜬 DB를 삭제하고 다시 만들거나 다른 서버에 DB를 만들경우엔 스크립트를 바로 실행하면 됨.


2. DATA 포함 전체 복제를 원할 경우

복제할 DB와 똑같은 구조의 Database를 만들어 주고 dump & load 하면 됨.

단, Database 만들 시에 segment 순서를 맞춰서 만들어주어야 한다.


※ 순서확인하여 Database 만들기.

1. 복제할 DB의 dbid를 알아낸다.
    select db_id('database_name')
    go

2. DB의 page size를 알아낸다. (DB create 시 size를 page 단위로 할 것이면 이 부분은 생략해도 됨.)
    select @@maxpagesize (or select @@pagesize)

3. segment 순서 및 크기를 알아낸다.(아래는 page size 가 2K인 경우)
    select dbid, segmap, size/512 from master..sysusages where dbid = 번호(1에서 알아낸 번호)
※ page 단위가 2K 인 DB에서 size/512 하면 MB단위의 숫자를 얻을 수 있다.

4. 3에서 알아낸 segment 순서 및 크기에 맞춰 Database 생성
    (segmap 번호가 3은 data 영역을 의미, 4는 log영역을 의미)

[example]
> select dbid, segmap, size/512 from master..sysusages where dbid=11
    dbid    segmap    size
    ----   --------   ------
     11          3           100
     11          4            50
     11          3           100
     11          3           100
     11          4            50

정보가 위와 같을 때 DB 생성 방법
(Load 목적으로 DB만들 시 마지막에 for load 옵션을 주면 빠르게 DB 생성할 수 있다.)


case1) 그냥 순서대로 다 만들어준다.

create database ABC_DB on ABC_dev = '100M' log on ABC_log = '50M' for load
go

alter database ABC_DB on ABC_dev = '100M' for load
go

alter database ABC_DB on ABC_dev = '100M' for load
go

alter database ABC_DB log on ABC_log = '50M' for load
go


case2) 연속으로 된 것은 하나로 묶어줘도 된다. (단, device용량이 받쳐줬을 때....)

create database ABC_DB on ABC_dev = '100M' log on ABC_log = '50M' for load
go

alter database ABC_DB on ABC_dev = '200M' for load
go

alter database ABC_DB log on ABC_log = '50M' for load
go


case3) 순서만 맞으면 묶을 수 있는 것 다 묶어줘도 된다. (단, device용량이 받쳐줬을 때....)

create database ABC_DB on ABC_dev = '100M' log on ABC_log = '50M' for load
go

alter database ABC_DB on ABC_dev = '200M' log on ABC_log = '50M' for load
go


※ Dump & Load 하기.

 
dump database source_db_name to 'file_name'

load database target_db_name from 'file_name'


※ for load 옵션으로 DB를 만들었다면, load가 끝난 후 online database db_name 을 해주어야 한다.

'ASE' 카테고리의 다른 글

DB copy 방법  (0) 2009/07/07
ASE 단계별 실행 명령  (0) 2009/07/07
dbcc traceon(3504)을 걸었을 경우 나타날 수 있는 error 메세지  (0) 2009/07/06
ddlgen  (0) 2009/07/06
특정 client에게 정해진 IP에서만 login 허용 설정  (0) 2009/07/03
ASE 점검 방법  (0) 2009/07/01

ASE 단계별 실행 명령

ASE 2009/07/07 11:00 posted by 클리어리
[실행권한 : sa]

sp_addlogin loginame, passwd [, defdb]
                     [, deflanguage ] [, fullname ] [, passwdexp ]                             
                     [, minpwdlen ] [, maxfailedlogins ]
( 새로운 login 등록,  system table : master..syslogins 에 저장 )
- defdb : default db 설정
- deflanguage : default 언어 설정
- fullname : 식별용 이름 설정
- passwdexp : 암호 만료 기간 (단위 : 일), 가능한 값 : between 0 and 32767 
- minpwdlen : 암호 최소 길이 (between 0 and 30 characters)
- maxfailedlogins : 암호 최대 실패 허용 횟수 (between 0 and 32767)

sp_droplogin loginame
(login 삭제)

sp_displaylogin login_name
(login 정보 확인, 접속한 login으로 sp_displaylogin 하면 자신의 정보를 보여줌.)

sp_activeroles
(login한 자신에게 주어진 role list를 보여준다.)

sp_modifylogin account, column, value
( account에 대한 수정 )
 ※ option 종류
    - authenticate with
    - defdb
    - deflanguage
    - fullname
    - "add default role"
    - "drop default role"
    - "passwd expiration"
    - "min passwd length"
    - "max failed_logins"
    - login script

 [example]
 1) login script 등록 (ASE 12.5.x 부터 가능)
    : sp_modifylogin loginame, 'login script', user-defiened-procedure_name
 2) default db 변경
    : sp_modifylogin sarah, defdb, "pubs2"
 3) default language 변경
    : sp_modifylogin claire, deflanguage, "french"
 4) fullname 변경 ( login_name 이나 user_name 을 바꾸는 것이 아니다. 
                          등록정보에서 참고 이름정도로 생각하면 될 것 같다. )
    : sp_modifylogin clemens, fullname, "Samuel Clemens"
 5) user 가 login 하였을 때 가질 activated role 을 추가
    : sp_modifylogin csmith, "add default role", specialist_role
 6) 5)와 반대
    : sp_modifylogin hpillai, "drop default role", intern_role
 7) login 실수 최대 허용 횟수, 아래는 실수가 40번이 넘으면 해당 login은 lock이 걸린다.
    : sp_modifylogin "joe", "max failed_logins", "40"
 8) 모든 login에 대한 login 실수 최대 허용횟수를 3으로 덮어써버려라. 기존값 지워진다.
    : sp_modifylogin "all overrides", "max failed_logins", "3"
 9) 모든 login에 대하여 login 실수 최대 허용횟수 옵션을 제거하라.
    : sp_modifylogin "all overrides", "max failed_logins", "-1"
 10) nightlyjob는 local ASE 만 사용할 수 있고, 외부 LDAP, PAM 같은 것은 사용 못함.
    : sp_modifylogin "nightlyjob", "authenticate with", "ASE"

create role
drop role
(system table : master..syssrvroles 에 저장)

-------------------------------------------------------------------------------------- (ASE)

[실행권한 : dbo]

sp_changedbowner user_name
(dbo 바꾸기 : user_name에게 DB소유권을 넘긴다.)

sp_adduser loginame
(login list 중에서 DB 사용자 추가, system table : sysusers)

sp_dropuser username
(등록된 user 삭제)

sp_helpuser
(DB에 등록된 user 확인)

sp_addalias loginame, name_in_db
( 해당DB에 등록되어 있지는 않지만 등록된 user처럼 사용할 수 있게 하는 것,
  system table : sysalternates )

sp_dropalias
loginame
(등록되어 있는 alias 삭제)

sp_addgroup grpname   
(group 추가)

sp_helpgroup
(해당 DB에 존재하는 group 정보 조회)

sp_dropgroup grpname   
(등록된 group 삭제)

sp_changegroup grpname, username
(user 의 group을 바꾸기)

※ default group : public group <-- DB에 user으로 등록이 되면 자동으로 public group에 속하게 된다.
    한 user는 public group 포함 2개의 group 에만 속할 수 있다. 즉, user define 한 group에는 하나에만
    속할 수 있다.


setuser 'user_name'
(user 바꾸기, login을 바꾸는 것은 아님.
 ex) 현재 dbo으로 해당 DB에 접속되어 있는데 test_user01 이라는 user으로 바꾸고 싶을 때)

-------------------------------------------------------------------------------- (Database)

[실행권한 : dbo]

  grant    create table/view/rule/default/sp_~   to    user / group
[revoke]                                                      from user / group

(system table : sysprotects 에 저장)

sp_helprotect user_name
(user가 object에 대한 권한 목록을 보여준다.)

--------------------------------------------------------------------------------- (Objects)

[실행권한 : object owner]

  grant    select/insert/update/delete/reference/execute/all on object_name  to    user / group
[revoke]                                                                                                from user / group

(system table : sysprotects 에 저장)

sp_helprotect user_name
(user가 object에 대한 권한 목록을 보여준다.)

----------------------------------------------------------------------------------- (Data)

'ASE' 카테고리의 다른 글

DB copy 방법  (0) 2009/07/07
ASE 단계별 실행 명령  (0) 2009/07/07
dbcc traceon(3504)을 걸었을 경우 나타날 수 있는 error 메세지  (0) 2009/07/06
ddlgen  (0) 2009/07/06
특정 client에게 정해진 IP에서만 login 허용 설정  (0) 2009/07/03
ASE 점검 방법  (0) 2009/07/01