sqlserver7.0 데이타베이스
DESCRIPTION
TRANSCRIPT
1
6.Creating Database
데이터 저장 방식데이터베이스 생성하기데이터베이스 조작하기파일그룹 생성데이터 타입 생성테이블 생성스크립트 이용도서관 데이터베이스Practice
2
데이터 저장 방식
Extent (8 contiguous 8-KB pages)
Page (8 KB)
Tables,Indexes
Data
DatabaseDatabase
Data (file).mdf or .ndf
Data (file).mdf or .ndf
Log (file).ldf
Log (file).ldf
Max row size = 8060 bytes
3
보충설명
- 모든 데이터베이스는 주 데이터 파일 (.mdf) 를 가지고 하나
또는 그 이상의 로그파일 (.ldf) 을 가진다 . 데이터베이스는 두번
째 데이터베이스 파일 (ndf) 을 가질 수 있다 .
- 데이터베이스를 만들면 model 데이터베이스의 시스템 테이블
이 데이터베이스로 복사된다 . 따라서 데이터베이스는 최소한
model 데이터베이스보다 크거나 같게 된다 .
-Row cannot span pages. 따라서 하나의 행에 넣을 수 있는 데이
터의 최대 크기는 8060 바이트이다 .( 오버헤드를 제외한 수치 )
- 테이블과 인텍스는 extent 에 저장되는대 extent 는 8 개의 연속
적인 페이지 따라서 64KB 이다 .
4
데이터베이스 생성하기데이터베이스 정의
데이터베이스 이름 데이터베이스 크기 데이터베이스가 저장될 파일
CREATE DATABASE sampleON PRIMARY ( NAME=sample_data, FILENAME='c:\mssql7\data\sample.mdf', SIZE=10MB, MAXSIZE=15MB, FILEGROWTH=20%) LOG ON ( NAME=sample_log, FILENAME='c:\mssql7\data\sample.ldf', SIZE=3MB, MAXSIZE=5MB, FILEGROWTH=1MB)
CREATE DATABASE sampleON PRIMARY ( NAME=sample_data, FILENAME='c:\mssql7\data\sample.mdf', SIZE=10MB, MAXSIZE=15MB, FILEGROWTH=20%) LOG ON ( NAME=sample_log, FILENAME='c:\mssql7\data\sample.ldf', SIZE=3MB, MAXSIZE=5MB, FILEGROWTH=1MB)
5
데이터베이스 옵션 선택
데이터베이스 옵션 선택자주 사용되는 옵션
dbo use only read only trunc. log on chkpt. autoshrink
데이터베이스 옵션 보기 sp_dboption, sp_helpdb, sp_spaceused
6
자주 사용되는 옵션
dbo use only - 데이터베이스의 사용을 데이터베이스 소유주로
제한한다 .
Read only - 데이터베이스를 읽기전용으로 정의한다 .
Select into/bulkcopy - 데이터베이스로 하여금 로그를 하지 않는
작업을 수행하도록 한다 .
Trunc.log on chkpt - 체크포인트 프로세서 후의 로그를 지운다 .
Autoshink - 데이터베이스 크기가 자동적으로 줄어들것인지를
결정한다 .
Single user - 데이터베이스에 대한 접근을 한번에 한사람으로
제한한다 .
7
데이터베이스 조작하기
데이터와 로그 파일의 크기 증가 조절하기트랜잭션 로그 확대데이터베이스나 파일 줄이기데이터베이스 제거
8
데이터와 로그 파일의 크기 증가 조절하기
7 MB7 MB
3 MB3 MB
ALTER DATABASE sample MODIFY FILE ( NAME = 'sample_log', SIZE = 10MB)GO
ALTER DATABASE sampleADD FILE (NAME = sample_data2 ,FILENAME='c:\mssql7\data\sample2.ndf',
SIZE=10MB ,MAXSIZE=20MB)GO
ALTER DATABASE sample MODIFY FILE ( NAME = 'sample_log', SIZE = 10MB)GO
ALTER DATABASE sampleADD FILE (NAME = sample_data2 ,FILENAME='c:\mssql7\data\sample2.ndf',
SIZE=10MB ,MAXSIZE=20MB)GO
9
보충설명
- ALTER DATABASE 문을 사용하기 위해서는 master database를
사용하고 있어야 한다 .
- 데이터베이스의 크기를 조절하는 방법
1. 데이터베이스와 로그파일이 자동으로 증가하도록 한다 .
2. 현재 존재하는 데이터베이스와 로그파일의 현재크기와 최대
크기를 수동으로 증가 시킨다 .
3. 수동으로 두 번째 데이터베이스와 로그파일을 추가한다 .
10
Transaction Log 가 작동하는 원리
Data modification is sent by application
Data modification is sent by application
1111
Disk
Modification is recorded in transaction log on disk
Modification is recorded in transaction log on disk
3333
Data pages are located in, or read into, buffer cache and modified
Data pages are located in, or read into, buffer cache and modified
2222
Buffer Cache
Disk
Checkpoint writes committed transactionsto database
Checkpoint writes committed transactionsto database
4444
11
트랜잭션 로그 확대
로그 감시필요 시 로그 크기 확대과부하 로그 생성 감시
다량의 데이터를 인덱스 테이블에 로딩 시 큰 트랜잭션 이미지나 텍스트 처리 수행 시
12
데이터베이스나 파일 줄이기
전체 데이터베이스 줄이기
데이터베이스내의 데이터 파일 줄이기
데이터베이스를 자동적으로 줄이기
DBCC SHRINKDATABASE (sample, 25)DBCC SHRINKDATABASE (sample, 25)
DBCC SHRINKFILE (sample_data, 10)DBCC SHRINKFILE (sample_data, 10)
13
데이터베이스 제거
제거 방법 SQL Server Enterprise Manager DROP 문장
데이터베이스 제거 시 제한 사항 복구 시 (Restored) 사용자 접근 시 (connecting to it) 복제에서 출판시 (Publishing)
DROP DATABASE northwind, pubsDROP DATABASE northwind, pubs
14
Leveraging the Windows NT Server Fault Tolerance
Using Disk Striping (RAID Level 0)
Using Disk Mirroring (RAID Level 1)
Using Disk Striping with Parity (RAID Level 5)
Using RAID with SQL Server
15
파일그룹 생성
northwind Databasenorthwind Database
Northwnd.mdf
C:\
Ordhist1.ndf Ordhist2.ndf
D:\
Northwnd.ldf
C:\
Default Filegroup OrderHistoryGroup
sys...sys...sys...sys...
sys...sys...sys...sys...
sysuserssysuserssysuserssysusers
sysobjectssysobjectssysobjectssysobjects
............
ordersordersordersorders
customerscustomerscustomerscustomers
productsproductsproductsproducts
ordhistyear2ordhistyear2ordhistyear2ordhistyear2
ordhistyear1ordhistyear1ordhistyear1ordhistyear1
16
보충설명 -1
- Filegroups are named collections of files
-With filegroups. You can locate specific objects on a specific file
Types of filegroups
-The default filegroup : contains the primary data file and any other
files that are not part of another filegroup. All system tables and all
tables and indexes for which a filegroup was not specified upon
creation are placed in the default filegroup
-User-defined filegroup: which are any filegroups that are specified
by using the FILEGROUP keyword in an ALTER DATABASE
17
보충설명 -2
예제 ) The following example creates a user-defined filegroup in thenorthwind database and adds a secondary data file to the user-defined filegroup
ALTER DATABASE northwind
ADD FILEGROUP orderhistorygroup
GO
ALTER DATABASE northwind
ADD FILE
( NAME = ‘ordhistyear1’,
FILENAME = ‘c:\mssql7\data\ordhist1.ndf’,
SIZE - 5 MB),
TO FILEGROUP orderhistorygroup
GO
18
데이터 타입 생성
시스템 지원 데이터 타입사용자 정의 데이터 타입의 생성과 제거
19
시스템 지원 데이터 타입
시스템 지원 데이터 타입 분류 이진 (Binary) - binary[ ], varbinary[ ] 문자형 (Character) - char[ ], varchar[ ] 유니코드 문자 (Unicode character)-nchar[ ], nvarchar[ ] 날짜와 시간 (Date and time) - Datetime, samlldatetime
Exact 와 Approximate Numeric Data Exact Numeric Data - decimal[(p[,s])], numeric[p[,s]] Approximate - float[(n)], real
20
추가적인 시스템 제공 데이터 타입
Global identifier uniqueidentifier
Integer int
Monetary money, smallmoney
Special bit, cursor, sysname, timestamp
Text and Image text, image
Unicode text ntext
21
사용자 정의 데이터 타입의 생성과 제거
생성
제거
사용자 정의 데이터 타입 생성 지침
EXEC sp_addtype isbn, 'smallint’, 'NOT NULL' EXEC sp_addtype zipcode, 'char(10)' EXEC sp_addtype longstring, 'varchar(63)'
EXEC sp_addtype isbn, 'smallint’, 'NOT NULL' EXEC sp_addtype zipcode, 'char(10)' EXEC sp_addtype longstring, 'varchar(63)'
EXEC sp_droptype isbn EXEC sp_droptype isbn
22
사용자 정의 데이터 타입 생성 지침
- 만약 칼럼의 길이가 변한다면 변하는 데이터 타입을 사용하라 .
예를 들면 , 이름의 리스트를 만들어야 한다면 , 고정된 char 보다
변할 수 있는 varchar 타입을 사용한다 .
- 숫자 데이터 타입에 대해서는 요구되는 크기와 정확도를 고려
한다 . 일반적으로는 decimal 을 사용한다 .
- 저장해야 되는 데이터가 8000 바이트보다 크다면 , text 나 image
테이터 타입을 사용하라 .(2GB 까지 저장가능 ).
23
테이블 생성
테이블 생성과 제거열의 추가와 제거 (SQL Server 7.0 의 추가기능 )
열 값의 생성
24
테이블 생성과 제거
Column nameColumn nameColumn nameColumn name Data typeData typeData typeData type NULL or NOT NULLNULL or NOT NULLNULL or NOT NULLNULL or NOT NULL
CREATE TABLE member(member_nolastnamefirstnamemiddleinitialphotograph)
CREATE TABLE member(member_nolastnamefirstnamemiddleinitialphotograph)
member_noshortstringshortstringletterimage
member_noshortstringshortstringletterimage
NOT NULL,NOT NULL,NOT NULL,NULL,NULL
NOT NULL,NOT NULL,NOT NULL,NULL,NULL
25
테이블의 생성
- 하나의 데이터베이스에 20 억 개의 테이블을 만들 수 있다 .
- 테이블 당 1024 개의 칼럼을 가질 수 있다 .
-NOT NULL 이 SQL Server 의 디폴트이다 .
테이블의 제거
- 테이블을 제거하기 전에 테이블과 다른 객체들과의 의존관계를
제거해야 한다 . 의존관계를 알아 볼려면 sp_depends 시스템 프로
시져를 사용한다 .
Syntax DROP TABLE table_name [,…n]
26
열의 추가와 제거
ALTER TABLE sales ADD customer_name char(30) null
ALTER TABLE sales ADD customer_name char(30) null
ALTER TABLE sales DROP COLUMN sales_date
ALTER TABLE sales DROP COLUMN sales_date
제거
CommissionCommission Sales_amountSales_amount Sales_dateSales_date Customer IDCustomer ID Customer_nameCustomer_name
27
열 값의 생성
IDENTITY 속성 이용 Seed 값 설정 increment value 설정 가장 최근의 값 이용 : @@identity
NEWID 함수와 식별자 데이터 타입의 이용 글로벌한 유일 값 DEFAULT 제약 이용
28
IDENTITY 속성 이용하기
문법
CREATE TABLE table (column_name data_type [IDENTITY [seed [
, increment] NOT NULL)
- 오직 하나의 칼럼만이 허용된다 .
- 갱신될 수 없다 .
- NULL 값을 허용하지 않는다 .
- integer(int, smallint, tinyint), numeric, decimal 형과 사용되어야 한다 .
-IDENT_SEED: seed, 시작값을 알려 준다 .
-IDENT_INCR: 증가값을 알려 준다 .
29
예제 )
In this example, the customer table customer ID column is created
with a uniqueidentifier data type, with a default value generated
by the NEWID function. A unique value for the cust_id column
will be generated for each new and existing row
CREATE TABLE customer
(cust_id uniqueidentifier NOT NULL
DEFAULT NEWID(),
Cust_name char(30) NOT NULL)
30
Transact-SQL 스크립트를 이용한 스키마 생성 백업용 스크립트 이용 개발용 스크립트를 생성하거나 업데이트 테스트용 혹은 개발용 환경의 생성 새로운 직원을 훈련
생성할 수 있는 것 전체 데이터베이스 테이블 스키마 테이블과 인덱스 스키마
스크립트 이용
31
권장 사항
Place Database and Transaction Log on Separate Physical Disks
Disable Write Caching on Disks Specify Maximum Size When You Use Automatic File Grow
thBack Up master Database After You Create or Modify a Dat
abaseGenerate Scripts to Re-create Database and Database Obje
cts
32
데이터 베이스 예제 - 도서관
도서관 데이터베이스 생성
33
스키마
isbnisbncopy_nocopy_notitle_notitle_noon_loanon_loan
copy
isbnisbntitle_notitle_notranslationtranslationcovercoverloanableloanable
item
title_notitle_notitletitleauthorauthorsynopsissynopsis
titlemember_nomember_nostreetstreetcitycitystatestatezipzipphone_nophone_noeaxpr_dateeaxpr_date
adultisbnisbnmember_nomember_nolog_datelog_dateremarksremarks
reservation
member_nomember_nolastnamelastnamefirstnamefirstnamemiddleinitialmiddleinitialphotographphotograph
member
member_nomember_noadult_member_noadult_member_nobirth_datebirth_date
juvenile
isbnisbncopy_nocopy_notitle_notitle_nomember_nomember_noout_dateout_datedue_datedue_date
loan
isbnisbncopy_nocopy_noout_dateout_datetitle_no title_no member_nomember_nodue_datedue_datein_datein_datefine_assessedfine_assessedfine_paidfine_paidfine_waivedfine_waivedremarksremarks
loanhist
34
Member Information
juvenilejuvenilejuvenilejuvenilemember_nomember_no adult_member_noadult_member_no birth_datebirth_date
PK, FKPK, FK FK, NNFK, NN NNNN345
345
211
211
Jun 01 1980Mar 01 1978Nov 05 1982
Jun 01 1980Mar 01 1978Nov 05 1982
adultadultadultadultmember_nomember_no streetstreet citycity statestate zipzip
PK,FKPK,FK NNNN NNNN NN NN NN NN126
126
Elm StBowery AveBowery Ave
Elm StBowery AveBowery Ave
SeattleSeattleKent
SeattleSeattleKent
WAWAWA
WAWAWA
980229802298206
980229802298206
phone_nophone_no
NULL(206)555-1212NULL
NULL(206)555-1212NULL
expr_dateexpr_date NN NN
Jun 06 1992Aug 07 1992Mar 03 1993
Jun 06 1992Aug 07 1992Mar 03 1993
membermembermembermembermember_nomember_no lastnamelastname firstnamefirstname middleinitialmiddleinitial photographphotograph
PKPK NNNN NNNN 123456
123456
AndersonBarrBarrAndersonAndersonHenson
AndersonBarrBarrAndersonAndersonHenson
AndrewAndrewBillBillSallyJack
AndrewAndrewBillBillSallyJack
ARNULLBANULL
ARNULLBANULL
~~~~~~~~~
~~~~~~
~~~~~~~~~
~~~~~~
35
Item Information
title_no copy_no on_loanisbn
112344
YYNYYY
121112
112344
copycopy
FK, NN NNPK, FK PK
PK FK, NN
isbn title_no translation cover loanable
12345
12342
EnglishFrenchFrenchNULLEnglish
softbackNULLhardbackhardbacksoftback
YNYNULLY
itemitem
PK NN
titletitletitle_no title author
NNsynopsis
1234
Gone With the WindColor PurpleHotelWinnie the Pooh
MitchellWalkerHaileyMilne
~~~~~~
~~~
36
Loan Information
reservationreservationreservationreservationisbnisbn member_nomember_no log_datelog_date
PK,FKPK,FK PK, FKPK, FK 114
114
233
233
3/7/1992NULL3/17/1992
3/7/1992NULL3/17/1992
remarksremarks
~~~NULL~~~
~~~NULL~~~
loanloanloanloanisbnisbn copy_nocopy_no title_notitle_no member_nomember_no out_dateout_date
PK,FK1PK,FK1 PK, FK1PK, FK1 FK,NNFK,NN FK, NN FK, NN PK, NNPK, NN14431
14431
11212
11212
14431
14431
11231
11231
03/18/9203/15/9203/17/9203/18/9203/15/92
03/18/9203/15/9203/17/9203/18/9203/15/92
due_datedue_date NN NN
03/29/9203/29/9204/01/9204/02/9203/29/92
03/29/9203/29/9204/01/9204/02/9203/29/92
loanhistloanhistloanhistloanhistisbnisbn copy_nocopy_no out_dateout_date
PK,FK1PK,FK1 PK, FK1PK, FK1 NN NN12211
12211
11121
11121
10/13/9107/07/9110/13/9111/06/9110/30/91
10/13/9107/07/9110/13/9111/06/9110/30/91
title_notitle_noFK,NNFK,NN
12211
12211
member_nomember_no FK, NN FK, NN
42431
42431
due_datedue_date
10/27/9107/21/9110/27/9111/20/9111/13/91
10/27/9107/21/9110/27/9111/20/9111/13/91
in_datein_date
10/26/91NULL10/28/9111/14/9111/15/91
10/26/91NULL10/28/9111/14/9111/15/91
fine_assessedfine_assessed
0.000.100.000.200.00
0.000.100.000.200.00
fine_paidfine_paid
0.000.000.000.200.00
0.000.000.000.200.00
fine_waivedfine_waived
0.000.100.000.000.00
0.000.100.000.000.00
remarksremarks
~~~~~~~~~~~~
~~~~~~~~~~~~
37
데이터베이스 만들기 (1)
DB 의 이름을 적는다 .
38
데이터베이스 만들기 (2)
트랜잭션로그를 적는다 .
39
테이블 만들기