레이블이 db인 게시물을 표시합니다. 모든 게시물 표시
레이블이 db인 게시물을 표시합니다. 모든 게시물 표시

2024년 6월 29일 토요일

ORACLE DB - INDEX

 
/***********************************************
  Oracle DB 인덱스 생성
   Oracle 19c 기준으로 작성되었습니다. 
***********************************************/



/***********************************************
 CUST, CUST_DTL 테이블, 인덱스 상태 조회
   STR 계정 접속
***********************************************/
SELECT
    OBJECT_TYPE,
    OBJECT_NAME,
    CREATED
FROM USER_OBJECTS
ORDER BY 2,1;



/***********************************************
 통계 정보 생성
   STR 계정 접속
***********************************************/
SELECT
    TABLE_NAME,
    TABLESPACE_NAME,
    LAST_ANALYZED
FROM USER_TABLES
ORDER BY 1;
-- 통계 정보 생성
EXEC DBMS_STATS.GATHER_TABLE_STATS(OWNNAME=>'STR', TABNAME=>'CUST');
EXEC DBMS_STATS.GATHER_TABLE_STATS(OWNNAME=>'STR', TABNAME=>'CUST_DTL');
-- 통계 정보 삭제
EXEC DBMS_STATS.DELETE_TABLE_STATS(OWNNAME=>'STR', TABNAME=>'CUST');
EXEC DBMS_STATS.DELETE_TABLE_STATS(OWNNAME=>'STR', TABNAME=>'CUST_DTL');



/***********************************************
 인덱스 추가 생성
  테이블명: CUST 
  인덱스명: CUST_X1(CUST_NM)
   STR 계정 접속
***********************************************/

SELECT *
FROM STR.CUST
WHERE CUST_NO = '20221125TKDN00000007';

-- CUST_NM 조회
-- 김영칠 3건, 김일영 2건, 김일삼 1건
SELECT *
FROM STR.CUST
WHERE CUST_NM = '김영칠';

CREATE INDEX STR.CUST_X1 ON STR.CUST
(CUST_NM)
TABLESPACE TS_STR_I;


SELECT
    TABLE_NAME,
    INDEX_NAME,
    COLUMN_NAME,
    COLUMN_POSITION
FROM USER_IND_COLUMNS
ORDER BY 1, 2;


/***********************************************
 FBI 인덱스 추가 생성
  테이블명: CUST 
  인덱스명: CUST_X1(CUST_NM)
   STR 계정 접속
***********************************************/
SELECT * 
FROM STR.CUST_DTL
WHERE MBL_NO = '015-0101-0101';
SELECT * 
FROM STR.CUST_DTL
WHERE MBL_NO = '01501010101';
SELECT
  MBL_NO,
  REPLACE(MBL_NO,'-','')
FROM STR.CUST_DTL;
SELECT * 
FROM STR.CUST_DTL
WHERE REPLACE(MBL_NO,'-','') = '01501010101';

CREATE INDEX STR.CUST_DTL_X1 ON STR.CUST_DTL
(REPLACE(MBL_NO,'-',''))
TABLESPACE TS_STR_I;
SELECT
    A.TABLE_NAME,
    A.INDEX_NAME,
    B.INDEX_TYPE,
    A.COLUMN_NAME,
    A.COLUMN_POSITION
FROM 
    USER_IND_COLUMNS A,
    USER_INDEXES B
WHERE A.TABLE_NAME = B.TABLE_NAME 
AND A.INDEX_NAME = B.INDEX_NAME
ORDER BY 1, 2;



-- 인덱스 삭제
DROP INDEX STR.CUST_X1;
DROP INDEX STR.CUST_DTL_X1;


[출처] DB보다


ORACLE DB - TABLESPACE, 계정


/***********************************************
  Oracle DB 계정 생성
  Oracle 19c 기준으로 작성되었습니다. 
***********************************************/

/***********************************************
  DB계정 상태 확인
***********************************************/
--DB계정 상태 확인
SELECT
    USERNAME,
    PROFILE,
    ACCOUNT_STATUS,
    DEFAULT_TABLESPACE,
    TEMPORARY_TABLESPACE,
    CREATED,
    EXPIRY_DATE
FROM DBA_USERS;


/***********************************************
  Tablespace 상태 확인
***********************************************/
-- Tablespace 상태 확인
SELECT 
    TABLESPACE_NAME, 
    FILE_NAME, 
    BYTES/1024/1024 AS "SIZE_MB"
FROM DBA_DATA_FILES;


/***********************************************
  Tablespace 생성
    데이터파일 위치 확인: /oracle/app/oracle/oradata/STR/
***********************************************/
-- 테이블 영역
CREATE TABLESPACE TS_STR_D
DATAFILE '/oracle/app/oracle/oradata/STR/TS_STR_D_001.DBF' SIZE 2048M;
-- 인덱스 영역
CREATE TABLESPACE TS_STR_I
DATAFILE '/oracle/app/oracle/oradata/STR/TS_STR_I_001.DBF' SIZE 2048M;


/***********************************************
  STR DB 계정 생성
***********************************************/
-- STR DB계정 생성
CREATE USER STR
IDENTIFIED BY "oracle"
DEFAULT TABLESPACE TS_STR_D
ACCOUNT UNLOCK;
-- STR DB계정 권한 생성
GRANT CONNECT, RESOURCE TO STR;


/***********************************************
  STR DB 계정 프로파일 변경
***********************************************/
-- DEFAULT 프로파일 상태 확인
SELECT 
    * 
FROM DBA_PROFILES
WHERE PROFILE = 'DEFAULT';

FAILED_LOGIN_ATTEMPTS        비밀번호 실패 허용 수
PASSWORD_LIFE_TIME             비밀번호 유효 기간  
PASSWORD_LOCK_TIME           비밀번호  잠김 시간
PASSWORD_GRACE_TIME        비밀번호 변경 메세지 출력 일자

-- PROFILE 설정 변경
ALTER PROFILE DEFAULT
LIMIT
FAILED_LOGIN_ATTEMPTS   UNLIMITED
PASSWORD_LIFE_TIME        UNLIMITED
PASSWORD_LOCK_TIME      UNLIMITED
PASSWORD_GRACE_TIME   UNLIMITED
;

-- PROFILE 설정 원복
ALTER PROFILE DEFAULT
LIMIT
FAILED_LOGIN_ATTEMPTS 10
PASSWORD_LIFE_TIME    180
PASSWORD_LOCK_TIME    1
PASSWORD_GRACE_TIME   7
;


/***********************************************
  STR DB 계정 삭제 및 테이블스페이스 삭제
***********************************************/
-- DB계정 삭제
DROP USER STR CASCADE;

-- 테이블스페이스 삭제
DROP TABLESPACE TS_STR_D INCLUDING CONTENTS AND DATAFILES;
DROP TABLESPACE TS_STR_I INCLUDING CONTENTS AND DATAFILES;
 

[출처] DB보다


2024년 6월 28일 금요일

ORACLE DB - SEQUENCE


/***********************************************

Oracle DB 계정 생성

Oracle 19c 기준으로 작성되었습니다.
***********************************************/

/********************************************************
시퀀스 생성
시퀀스명: SEQ_TEST_1
STR 계정 접속
********************************************************/

-- 시퀀스 생성
CREATE SEQUENCE STR.SEQ_TEST_1
MINVALUE 1
MAXVALUE 999999999
INCREMENT BY 1
START WITH 1
CACHE 20
ORDER
CYCLE;

-- 시퀀스 상태
SELECT
SEQUENCE_NAME,
LAST_NUMBER,
MIN_VALUE,
MAX_VALUE,
LENGTH(MAX_VALUE) AS "LENGTH",
INCREMENT_BY,
CYCLE_FLAG,
ORDER_FLAG,
CACHE_SIZE
FROM USER_SEQUENCES
WHERE SEQUENCE_NAME = 'SEQ_TEST_1';


/********************************************************
시퀀스 사용 방법
STR 계정 접속
********************************************************/

-- 시퀀스 다음 값 생성
SELECT STR.SEQ_TEST_1.NEXTVAL FROM DUAL;

-- 시퀀스 현재 상태 값
SELECT STR.SEQ_TEST_1.CURRVAL FROM DUAL;

-- 시퀀스 증가 번호 변경
ALTER SEQUENCE STR.SEQ_TEST_1 INCREMENT BY 1;

-- 시퀀스 시작 번호 변경
ALTER SEQUENCE STR.SEQ_TEST_1 RESTART START WITH 1;


/********************************************************
시퀀스 꿀팁
STR 계정 접속
********************************************************/

SELECT STR.SEQ_TEST_1.NEXTVAL FROM DUAL;

SELECT TO_CHAR(STR.SEQ_TEST_1.NEXTVAL,'FM000000000') FROM DUAL;

SELECT
TO_CHAR(SYSDATE, 'YYYYMMDD') ||
TO_CHAR(STR.SEQ_TEST_1.NEXTVAL, 'FM000000000')
FROM DUAL;


/********************************************************
테이블 생성(시퀀스 사용을 위한 테이블 생성)
STR 계정 접속
********************************************************/

-- 테이블 생성
CREATE TABLE STR.TEST
(
TEST_NO VARCHAR2(20)
)
TABLESPACE TS_STR_D;

-- 10건 데이터 입력
INSERT INTO STR.TEST
SELECT
TO_CHAR(SYSDATE, 'YYYYMMDD') ||
TO_CHAR(STR.SEQ_TEST_1.NEXTVAL, 'FM000000000') "TEST_NO"
FROM DUAL
CONNECT BY LEVEL <= 10;

COMMIT;

-- 데이터 조회
SELECT * FROM STR.TEST;

-- 시퀀스 현재 상태 값
SELECT STR.SEQ_TEST_1.CURRVAL FROM DUAL;

-- 시퀀스 증가 번호 변경
ALTER SEQUENCE STR.SEQ_TEST_1 INCREMENT BY 1;



/********************************************************
고객 번호 시퀀스 생성 예제
시퀀스명: SEQ_CUST_1
STR 계정 접속
********************************************************/

-- 시퀀스 생성
CREATE SEQUENCE STR.SEQ_CUST_1
MINVALUE 1
MAXVALUE 99999999
INCREMENT BY 1
START WITH 1
CACHE 20
ORDER
CYCLE;

-- 고객 번호 생성
SELECT
TO_CHAR(SYSDATE,'YYYYMMDD') ||
DBMS_RANDOM.STRING('U',4) ||
TO_CHAR(STR.SEQ_CUST_1.NEXTVAL,'FM00000000') AS "CUST_NO"
FROM DUAL
CONNECT BY LEVEL <= 5;

-- 오브젝트 삭제
SELECT
'DROP '||OBJECT_TYPE||' STR.'||OBJECT_NAME||';'
FROM USER_OBJECTS
WHERE OBJECT_NAME IN ('SEQ_CUST_1','SEQ_TEST_1','TEST');

[출처] DB보다


ORACLE DB - CREATE

 

/***********************************************
  Oracle DB 테이블 생성
   Oracle 19c 기준으로 작성되었습니다. 
***********************************************/


/***********************************************
 CUST(고객) 테이블 생성
 STR 계정 접속
***********************************************/
CREATE TABLE STR.CUST
(
	CUST_NO   VARCHAR2(20)    NOT NULL,
	CUST_NM   VARCHAR2(1000)  NOT NULL,
	JOIN_DY   VARCHAR2(8)     NULL,
	PASSWD    VARCHAR2(100)   NOT NULL,
	BRTH_DD   VARCHAR2(8)     NULL
)
TABLESPACE TS_STR_D;


CREATE UNIQUE INDEX STR.CUST_PK ON STR.CUST
(CUST_NO)
TABLESPACE TS_STR_I;


ALTER TABLE STR.CUST
ADD CONSTRAINT CUST_PK 
PRIMARY KEY(CUST_NO);


COMMENT ON TABLE  STR.CUST IS '고객';

COMMENT ON COLUMN STR.CUST.CUST_NO IS '고객번호';
COMMENT ON COLUMN STR.CUST.CUST_NM IS '고객명';
COMMENT ON COLUMN STR.CUST.JOIN_DY IS '가입일자';
COMMENT ON COLUMN STR.CUST.PASSWD IS '비밀번호';
COMMENT ON COLUMN STR.CUST.BRTH_DD IS '생년월일';


/***********************************************
 CUST_DTL(고객상세) 테이블 생성
 STR 계정 접속
***********************************************/

CREATE TABLE STR.CUST_DTL
(
	CUST_NO       VARCHAR2(20)   NOT NULL,
	MBL_NO        VARCHAR2(13)   NULL,
	HOME_ADDR     VARCHAR2(1000) NULL,
	ZIP_CD        VARCHAR2(10)   NULL,
	EMAIL         VARCHAR2(200)  NULL
)
TABLESPACE TS_STR_D;


CREATE UNIQUE INDEX STR.CUST_DTL_PK ON STR.CUST_DTL
(CUST_NO)
TABLESPACE TS_STR_I;

ALTER TABLE STR.CUST_DTL
ADD CONSTRAINT CUST_DTL_PK 
PRIMARY KEY(CUST_NO);


COMMENT ON TABLE  STR.CUST_DTL    IS '고객상세';

COMMENT ON COLUMN STR.CUST_DTL.CUST_NO IS '고객번호';
COMMENT ON COLUMN STR.CUST_DTL.MBL_NO IS '휴대폰번호';
COMMENT ON COLUMN STR.CUST_DTL.HOME_ADDR IS '집주소';
COMMENT ON COLUMN STR.CUST_DTL.ZIP_CD IS '우편번호';
COMMENT ON COLUMN STR.CUST_DTL.EMAIL IS '이메일';



/***********************************************
 테이블, 인덱스 상태 확인
 STR 계정 접속
***********************************************/
SELECT
    OBJECT_TYPE,
    OBJECT_NAME,
    CREATED
FROM USER_OBJECTS
ORDER BY 2,1;


/***********************************************
 테이블 상태 확인
 STR 계정 접속
***********************************************/

SELECT 
    A.TABLE_NAME, 
    B.COMMENTS AS "TABLE_COMMENT",
    A.COLUMN_NAME, 
    C.COMMENTS AS "COLUMN_COMMENT",
    A.COLUMN_ID 
FROM 
    USER_TAB_COLUMNS A,
    USER_TAB_COMMENTS B,
    USER_COL_COMMENTS C
WHERE A.TABLE_NAME = B.TABLE_NAME
AND A.TABLE_NAME = C.TABLE_NAME
AND A.COLUMN_NAME = C.COLUMN_NAME
ORDER BY A.TABLE_NAME, A.COLUMN_ID;




/***********************************************
 CUST(고객) 데이터 입력
 STR 계정 접속
***********************************************/
-- CUST(고객) 테이블 데이터 50건 입력
-- 데이터 특이사항 (김영일 3명, 김영칠 3명)

INSERT INTO STR.CUST VALUES('20221125JPYM00000001','김영일','20040101','flne5450','20000701');
INSERT INTO STR.CUST VALUES('20221125DROE00000002','김영이','20040101','npek0233','20000702');
INSERT INTO STR.CUST VALUES('20221125KJQN00000003','김영삼','20040305','zxet2771','20000703');
INSERT INTO STR.CUST VALUES('20221125WEGD00000004','김영사','20040305','tgli5670','20000704');
INSERT INTO STR.CUST VALUES('20221125AJKK00000005','김영오','20040405','iayw6265','20020705');
INSERT INTO STR.CUST VALUES('20221125LADR00000006','김영육','20040407','ohew6324','20020706');
INSERT INTO STR.CUST VALUES('20221125TKDN00000007','김영칠','20040507','jdsf1139','20020707');
INSERT INTO STR.CUST VALUES('20221125FGJP00000008','김영팔','20050207','pqmj2289','20020708');
INSERT INTO STR.CUST VALUES('20221125ZERM00000009','김영구','20050207','sgie6302','20020709');
INSERT INTO STR.CUST VALUES('20221125IOUS00000010','김일영','20050207','kyqd0483','20020710');
INSERT INTO STR.CUST VALUES('20221125FREG00000011','김일일','20051119','ljix4309','20020711');
INSERT INTO STR.CUST VALUES('20221125JXYA00000012','김일이','20060119','vzvi3915','20050712');
INSERT INTO STR.CUST VALUES('20221125ANQL00000013','김일삼','20060119','dzid2179','19620713');
INSERT INTO STR.CUST VALUES('20221125IKVD00000014','김일사','20060119','cmuf6339','19620714');
INSERT INTO STR.CUST VALUES('20221125ABAI00000015','김일오','20060119','zysq7590','19620715');
INSERT INTO STR.CUST VALUES('20221125YXTK00000016','김일육','20060119','ykwm7623','19620716');
INSERT INTO STR.CUST VALUES('20221125OHAF00000017','김일칠','20060225','qsne5403','19550717');
INSERT INTO STR.CUST VALUES('20221125SAVG00000018','김일팔','20060225','vzsa4413','19550718');
INSERT INTO STR.CUST VALUES('20221125APRV00000019','김일구','20090225','zums3447','19550719');
INSERT INTO STR.CUST VALUES('20221125XCRU00000020','김일영','20090225','xjvz8461','19550720');
INSERT INTO STR.CUST VALUES('20221125XUZN00000021','김이일','20090508','axov6969','20010801');
INSERT INTO STR.CUST VALUES('20221125RFSZ00000022','김이가','20090508','fitu9267','20010802');
INSERT INTO STR.CUST VALUES('20221125GSUH00000023','김이삼','20090508','pqnw5647','20010803');
INSERT INTO STR.CUST VALUES('20221125MNCU00000024','김이사','20090508','rviv2232','20010804');
INSERT INTO STR.CUST VALUES('20221125ZFMC00000025','김이오','20100217','omor3320','19910805');
INSERT INTO STR.CUST VALUES('20221125XUGB00000026','김이육','20100217','iwcm7473','19910806');
INSERT INTO STR.CUST VALUES('20221125CIGG00000027','김이칠','20100217','ultb6084','19910807');
INSERT INTO STR.CUST VALUES('20221125NNXY00000028','김이팔','20100217','ixwx3137','19910808');
INSERT INTO STR.CUST VALUES('20221125VZWP00000029','김이구','20100217','tpin3069','19830809');
INSERT INTO STR.CUST VALUES('20221125CLJU00000030','김삼영','20100217','olha1635','19830810');
INSERT INTO STR.CUST VALUES('20221125AVME00000031','김삼일','20120602','dyho5331','19880811');
INSERT INTO STR.CUST VALUES('20221125NYAA00000032','김영칠','20120602','jfly1680','19980812');
INSERT INTO STR.CUST VALUES('20221125UDXV00000033','김삼삼','20120602','ydeo9942','19980813');
INSERT INTO STR.CUST VALUES('20221125WYVA00000034','김삼사','20120602','fylt4787','19980814');
INSERT INTO STR.CUST VALUES('20221125CFTF00000035','김삼오','20120602','aoyd7537','19670815');
INSERT INTO STR.CUST VALUES('20221125SQXC00000036','김삼육','20120602','waaz3678','19670816');
INSERT INTO STR.CUST VALUES('20221125SQWO00000037','김삼칠','20220102','maat3026','19670817');
INSERT INTO STR.CUST VALUES('20221125ZMPZ00000038','김영일','20220102','iuzn5413','19670818');
INSERT INTO STR.CUST VALUES('20221125AYGK00000039','김삼구','20220102','mwzc8562','19670819');
INSERT INTO STR.CUST VALUES('20221125THBX00000040','김사영','20220102','tvgz0417','19750820');
INSERT INTO STR.CUST VALUES('20221125MDBK00000041','김사일','20220115','alvz3064','19750901');
INSERT INTO STR.CUST VALUES('20221125LTYY00000042','김사가','20220115','xuhp4988','19750902');
INSERT INTO STR.CUST VALUES('20221125FPUV00000043','김사삼','20220115','ssly9245','19750903');
INSERT INTO STR.CUST VALUES('20221125CHXS00000044','김사사','20220415','glzn5012','19750904');
INSERT INTO STR.CUST VALUES('20221125MJTM00000045','김사오','20220415','tlht5713','19700905');
INSERT INTO STR.CUST VALUES('20221125LQZU00000046','김사육','20220415','whtk7257','19700906');
INSERT INTO STR.CUST VALUES('20221125CEGQ00000047','김사칠','20220808','xamu3455','19960907');
INSERT INTO STR.CUST VALUES('20221125FWXP00000048','김사팔','20220808','uxub8838','19960908');
INSERT INTO STR.CUST VALUES('20221125JVPE00000049','김영칠','20220808','vnry4863','19960909');
INSERT INTO STR.CUST VALUES('20221125JWBX00000050','김영일','20220808','kdlb3873','19960910');

COMMIT;


/***********************************************
 CUST_DTL(고객상세) 데이터 입력
  STR 계정 접속
***********************************************/
-- CUST_DTL(고객상세) 테이블 데이터 50건 입력
-- 데이터 특이사항 NULL값 4건, Empty String값 4건

INSERT INTO STR.CUST_DTL VALUES('20221125JPYM00000001','015-0101-0101','서울시 강남구 압구정동','06000','uljbou@superemail.com');
INSERT INTO STR.CUST_DTL VALUES('20221125DROE00000002','015-0101-0102','서울시 강남구 압구정동','06000','oldbic@superemail.com');
INSERT INTO STR.CUST_DTL VALUES('20221125KJQN00000003','015-0101-0103','서울시 강남구 압구정동','06000','wbojex@superemail.com');
INSERT INTO STR.CUST_DTL VALUES('20221125WEGD00000004','015-0101-0104','서울시 강남구 압구정동','06000','yhilhj@superemail.com');
INSERT INTO STR.CUST_DTL VALUES('20221125AJKK00000005','015-0101-0105','서울시 강남구 압구정동','06000','tasorz@superemail.com');
INSERT INTO STR.CUST_DTL VALUES('20221125LADR00000006','015-0101-0106','서울시 강남구 청담동','06074','wizgkj@superemail.com');
INSERT INTO STR.CUST_DTL VALUES('20221125TKDN00000007','015-0101-0107','서울시 강남구 청담동','06074','zvrexd@superemail.com');
INSERT INTO STR.CUST_DTL VALUES('20221125FGJP00000008','015-0101-0108','서울시 강남구 청담동','06074','ribait@superemail.com');
INSERT INTO STR.CUST_DTL VALUES('20221125ZERM00000009','015-0101-0109','서울시 강남구 청담동','06074','zuhzaq@superemail.com');
INSERT INTO STR.CUST_DTL VALUES('20221125IOUS00000010','015-0101-0110','서울시 강남구 청담동','06074','gnlcqg@superemail.com');
INSERT INTO STR.CUST_DTL VALUES('20221125FREG00000011','015-0101-0111','서울시 강남구 도곡동','06294','tcoesv@metajjemail.com');
INSERT INTO STR.CUST_DTL VALUES('20221125JXYA00000012','015-0101-0112','서울시 강남구 도곡동','06294','gwuujt@metajjemail.com');
INSERT INTO STR.CUST_DTL VALUES('20221125ANQL00000013','015-0101-0113','서울시 강남구 도곡동','06294','mzsgxy@metajjemail.com');
INSERT INTO STR.CUST_DTL VALUES('20221125IKVD00000014','015-0101-0114','서울시 강남구 도곡동','06294','evmcrl@metajjemail.com');
INSERT INTO STR.CUST_DTL VALUES('20221125ABAI00000015','015-0101-0115','서울시 강남구 도곡동','06294','fnbvau@metajjemail.com');
INSERT INTO STR.CUST_DTL VALUES('20221125YXTK00000016','015-0101-0116','서울시 강남구 신사동','06027','vqfsez@metajjemail.com');
INSERT INTO STR.CUST_DTL VALUES('20221125OHAF00000017','015-0101-0117','서울시 강남구 신사동','06027','scwfrs@metajjemail.com');
INSERT INTO STR.CUST_DTL VALUES('20221125SAVG00000018','015-0101-0118','서울시 강남구 신사동','06027','fsjzna@metajjemail.com');
INSERT INTO STR.CUST_DTL VALUES('20221125APRV00000019','015-0101-0119','서울시 강남구 신사동','06027','dcearf@metajjemail.com');
INSERT INTO STR.CUST_DTL VALUES('20221125XCRU00000020','015-0101-0120','서울시 강남구 신사동','06027','czpqas@metajjemail.com');
INSERT INTO STR.CUST_DTL VALUES('20221125XUZN00000021','015-0101-0121','서울시 서초구 반포동','06547','pcnann@gonnemail.com');
INSERT INTO STR.CUST_DTL VALUES('20221125RFSZ00000022','015-0101-0122','서울시 서초구 반포동','06547','sebplp@gonnemail.com');
INSERT INTO STR.CUST_DTL VALUES('20221125GSUH00000023','015-0101-0123','서울시 서초구 반포동','06547','rknvcf@gonnemail.com');
INSERT INTO STR.CUST_DTL VALUES('20221125MNCU00000024','015-0101-0124','서울시 서초구 반포동','06547','miqfws@gonnemail.com');
INSERT INTO STR.CUST_DTL VALUES('20221125ZFMC00000025','015-0101-0125','서울시 서초구 반포동','06547','zxpvie@gonnemail.com');
INSERT INTO STR.CUST_DTL VALUES('20221125XUGB00000026','015-0101-0126','서울시 강남구 대치동','06284','shfjff@gonnemail.com');
INSERT INTO STR.CUST_DTL VALUES('20221125CIGG00000027','015-0101-0127','서울시 강남구 대치동','06284','gyxloz@gonnemail.com');
INSERT INTO STR.CUST_DTL VALUES('20221125NNXY00000028','015-0101-0128','서울시 강남구 대치동','06284','qunrwt@gonnemail.com');
INSERT INTO STR.CUST_DTL VALUES('20221125VZWP00000029','015-0101-0129','서울시 강남구 대치동','06284','koigww@gonnemail.com');
INSERT INTO STR.CUST_DTL VALUES('20221125CLJU00000030','015-0101-0130','서울시 강남구 대치동','06284','koacww@gonnemail.com');
INSERT INTO STR.CUST_DTL VALUES('20221125AVME00000031','015-0101-0131','부산광역시 해운대구 중동','48099','rkmhzr@narademail.com');
INSERT INTO STR.CUST_DTL VALUES('20221125NYAA00000032','015-0101-0132','부산광역시 해운대구 중동','48099','vxikgq@narademail.com');
INSERT INTO STR.CUST_DTL VALUES('20221125UDXV00000033','015-0101-0133','부산광역시 해운대구 중동','48099','ecddxs@narademail.com');
INSERT INTO STR.CUST_DTL VALUES('20221125WYVA00000034','015-0101-0134','부산광역시 해운대구 중동','48099','mjmxcf@narademail.com');
INSERT INTO STR.CUST_DTL VALUES('20221125CFTF00000035','015-0101-0135','부산광역시 해운대구 중동','48099','bdwfmb@narademail.com');
INSERT INTO STR.CUST_DTL VALUES('20221125SQXC00000036','015-0101-0136','부산광역시 해운대구 우동','48092','byjkso@narademail.com');
INSERT INTO STR.CUST_DTL VALUES('20221125SQWO00000037','015-0101-0137','부산광역시 해운대구 우동','48092',' ');
INSERT INTO STR.CUST_DTL VALUES('20221125ZMPZ00000038','015-0101-0138','부산광역시 해운대구 우동','48092',' ');
INSERT INTO STR.CUST_DTL VALUES('20221125AYGK00000039','015-0101-0139','부산광역시 해운대구 우동','48092','');
INSERT INTO STR.CUST_DTL VALUES('20221125THBX00000040','015-0101-0140','부산광역시 해운대구 우동','48092','');
INSERT INTO STR.CUST_DTL VALUES('20221125MDBK00000041','015-0101-0141','부산광역시 부산진구 부전동','47300','twvruy@qoodaemail.com');
INSERT INTO STR.CUST_DTL VALUES('20221125LTYY00000042','015-0101-0142','부산광역시 부산진구 부전동','47300','fvovzz@qoodaemail.com');
INSERT INTO STR.CUST_DTL VALUES('20221125FPUV00000043','015-0101-0143','','47300','vwyein@qoodaemail.com');
INSERT INTO STR.CUST_DTL VALUES('20221125CHXS00000044','015-0101-0144','','47300','yqavsm@qoodaemail.com');
INSERT INTO STR.CUST_DTL VALUES('20221125MJTM00000045','015-0101-0145','부산광역시 부산진구 부전동','47300','adrwte@qoodaemail.com');
INSERT INTO STR.CUST_DTL VALUES('20221125LQZU00000046','015-0101-0146',' ','48230','zkionw@qoodaemail.com');
INSERT INTO STR.CUST_DTL VALUES('20221125CEGQ00000047','015-0101-0147',' ','48230','cpkghk@qoodaemail.com');
INSERT INTO STR.CUST_DTL VALUES('20221125FWXP00000048','015-0101-0148','부산광역시 수영구 수영동','48230','메일주소');
INSERT INTO STR.CUST_DTL VALUES('20221125JVPE00000049','999-9999-9999','몰라','48230','난아싸라@이메일이없어요');
INSERT INTO STR.CUST_DTL VALUES('20221125JWBX00000050','000-0000-0000','님 마음속','48230','이메일');

COMMIT;




/***********************************************
 데이터 입력 에러 해결 방법(ORA-01950)
 SYS 계정 접속
***********************************************/

-- ORA-01950: 테이블스페이스 'TS_STR_D'에 대한 권한이 없습니다.

-- TS_STR_D 테이블스페이스 권한 생성
GRANT UNLIMITED TABLESPACE TO STR;

-- 권한 확인
SELECT * 
FROM DBA_SYS_PRIVS 
WHERE GRANTEE='STR';


-- TS_STR_D 테이블스페이스 권한 원복 
REVOKE UNLIMITED TABLESPACE FROM STR;

-- 권한 확인
SELECT * 
FROM DBA_SYS_PRIVS 
WHERE GRANTEE='STR';


/***********************************************
 SQL 실행
 STR 계정 접속
***********************************************/

SELECT
    A.CUST_NO,
    A.CUST_NM,
    A.BRTH_DD,
    B.MBL_NO,
    B.HOME_ADDR,
    B.EMAIL
FROM 
    STR.CUST A,
    STR.CUST_DTL B
WHERE A.CUST_NO = B.CUST_NO
AND A.CUST_NM = '김영구';
--AND A.CUST_NM IN ('김영구','김이오','김일구');



/***********************************************
 CUST(고객), CUST_DTL(고객상세) 데이터 삭제
 STR 계정 접속
***********************************************/

TRUNCATE TABLE STR.CUST;
TRUNCATE TABLE STR.CUST_DTL;


/***********************************************
 CUST(고객), CUST_DTL(고객상세) 테이블 삭제
 STR 계정 접속
***********************************************/

DROP TABLE STR.CUST;
DROP TABLE STR.CUST_DTL;

[출처] DB보다


2020년 6월 4일 목요일

DB - MSSQL - SP Help



sp_help
sp_columns
sp_who
sp_lock
sp_helptext
sp_helpindex
sp_spaceused
set statistics io on
select top 10 * from


2020년 5월 8일 금요일

DB - MSSQL - INFORMATION_SCHEMA #1




--------------------------------------------
-- SP, FN
--------------------------------------------
SELECT *
FROM sysobjects AS a
LEFT JOIN syscomments AS b ON a.id = b.id
WHERE a.type in ('P','FN')
AND b.text LIKE '%TB_YSARANGLOGIN%'




--------------------------------------------
-- TABLE
--------------------------------------------
SELECT 'DB' as [DataBase명]
, c.[TABLE_NAME] AS [테이블명(물리명)]
        , d.[TDescription] AS [테이블상세설명]
        , c.[COLUMN_NAME] AS [컬럼명(물리명)]
        , d.[CDescription] AS [컬럼상세설명]
        , (
               CASE WHEN c.[CHARACTER_MAXIMUM_LENGTH] IS NOT NULL AND c.[DATA_TYPE] IN ('varchar', 'nvarchar', 'char') THEN c.[DATA_TYPE] + '(' + CONVERT(VARCHAR, c.[CHARACTER_MAXIMUM_LENGTH]) + ')'
               ELSE c.[DATA_TYPE] END
        ) AS [데이터타입]
        , c.[IS_NULLABLE] AS [NULL여부]
        , (
               CASE WHEN p.[table] IS NOT NULL AND f.[referenced_table] IS NOT NULL THEN 'PFK'
               WHEN p.[table] IS NOT NULL AND f.[referenced_table] IS NULL THEN 'PK'
               WHEN p.[table] IS NULL AND f.[referenced_table] IS NOT NULL THEN 'FK'
               ELSE NULL END
        ) AS [KeyInfo]
        , f.[referenced_table] AS [부모테이블]
        , f.[referenced_column] AS [부모컬럼]
FROM INFORMATION_SCHEMA.TABLES t
        INNER JOIN INFORMATION_SCHEMA.COLUMNS c ON c.[TABLE_NAME] = t.[TABLE_NAME] AND t.[TABLE_TYPE] = 'BASE TABLE'
        LEFT OUTER JOIN (
               SELECT st.[name] AS [table],
                       sept.[value] AS [tdescription],
                       sc.[name] AS [column],
                       sepc.[value] AS [cdescription]
               FROM sys.tables st
                       INNER JOIN sys.columns sc ON st.[object_id] = sc.[object_id]
                       LEFT OUTER JOIN sys.extended_properties sept ON st.[object_id] = sept.[major_id]
                              AND sept.[minor_id] = 0
                              AND sept.[name] = 'MS_Description'
                       LEFT OUTER JOIN sys.extended_properties sepc ON st.[object_id] = sepc.[major_id]
                              AND sc.[column_id] = sepc.[minor_id]
                              AND sepc.[name] = 'MS_Description'
        ) d ON d.[Table] = c.[TABLE_NAME] AND d.[Column] = c.[COLUMN_NAME]
        LEFT OUTER JOIN (
               SELECT DISTINCT tab1.[name] AS [table],
                       col1.[name] AS [column],
                       tab2.[name] AS [referenced_table],
                       col2.[name] AS [referenced_column]
               FROM sys.foreign_key_columns fkc
                       INNER JOIN sys.tables tab1 ON tab1.[object_id] = fkc.[parent_object_id]
                       INNER JOIN sys.columns col1 ON col1.[column_id] = parent_column_id AND col1.[object_id] = tab1.[object_id]
                       INNER JOIN sys.tables tab2 ON tab2.[object_id] = fkc.[referenced_object_id]
                       INNER JOIN sys.columns col2 ON col2.[column_id] = referenced_column_id AND col2.[object_id] = tab2.[object_id]
        ) f ON f.[table] = t.[TABLE_NAME] AND f.[column] = c.[COLUMN_NAME]
        LEFT OUTER JOIN (
               SELECT OBJECT_NAME(ic.[OBJECT_ID]) AS [table],
                       COL_NAME(ic.[OBJECT_ID], ic.[column_id]) AS [column]
               FROM sys.indexes AS i
                       INNER JOIN sys.index_columns AS ic ON i.[OBJECT_ID] = ic.[OBJECT_ID] AND i.[index_id] = ic.[index_id]
               WHERE i.[is_primary_key] = 1
        ) p ON p.[table] = t.[TABLE_NAME] AND p.[column] = c.[COLUMN_NAME]
-- WHERE c.[TABLE_NAME] IN ('CARDAPP2020', 'UBE_Documents', 'MCMCANCEL', 'GROW_HEIGHTWEIGHT_2ND', 'MUKKEUMMAIN')
ORDER BY c.[TABLE_NAME]



--------------------------------------------
-- VIEW TABLE
--------------------------------------------
SELECT 'DB' as [DataBase명]
, c.[TABLE_NAME] AS [테이블명(물리명)]
        , d.[TDescription] AS [테이블상세설명]
        , c.[COLUMN_NAME] AS [컬럼명(물리명)]
        , d.[CDescription] AS [컬럼상세설명]
        , (
               CASE WHEN c.[CHARACTER_MAXIMUM_LENGTH] IS NOT NULL AND c.[DATA_TYPE] IN ('varchar', 'nvarchar', 'char') THEN c.[DATA_TYPE] + '(' + CONVERT(VARCHAR, c.[CHARACTER_MAXIMUM_LENGTH]) + ')'
               ELSE c.[DATA_TYPE] END
        ) AS [데이터타입]
        , c.[IS_NULLABLE] AS [NULL여부]
        , (
               CASE WHEN p.[table] IS NOT NULL AND f.[referenced_table] IS NOT NULL THEN 'PFK'
               WHEN p.[table] IS NOT NULL AND f.[referenced_table] IS NULL THEN 'PK'
               WHEN p.[table] IS NULL AND f.[referenced_table] IS NOT NULL THEN 'FK'
               ELSE NULL END
        ) AS [KeyInfo]
        , f.[referenced_table] AS [부모테이블]
        , f.[referenced_column] AS [부모컬럼]
--FROM INFORMATION_SCHEMA.TABLES t
FROM INFORMATION_SCHEMA.VIEWS t
INNER JOIN INFORMATION_SCHEMA.COLUMNS c ON c.[TABLE_NAME] = t.[TABLE_NAME] --AND t.[TABLE_TYPE] = 'BASE TABLE'
LEFT OUTER JOIN (
    SELECT st.[name] AS [table],
            sept.[value] AS [tdescription],
            sc.[name] AS [column],
            sepc.[value] AS [cdescription]
    FROM sys.tables st
    INNER JOIN sys.columns sc ON st.[object_id] = sc.[object_id]
    LEFT OUTER JOIN sys.extended_properties sept ON st.[object_id] = sept.[major_id]
            AND sept.[minor_id] = 0
            AND sept.[name] = 'MS_Description'
    LEFT OUTER JOIN sys.extended_properties sepc ON st.[object_id] = sepc.[major_id]
            AND sc.[column_id] = sepc.[minor_id]
            AND sepc.[name] = 'MS_Description'
) d ON d.[Table] = c.[TABLE_NAME] AND d.[Column] = c.[COLUMN_NAME]
LEFT OUTER JOIN (
    SELECT DISTINCT tab1.[name] AS [table],
            col1.[name] AS [column],
            tab2.[name] AS [referenced_table],
            col2.[name] AS [referenced_column]
    FROM sys.foreign_key_columns fkc
    INNER JOIN sys.tables tab1 ON tab1.[object_id] = fkc.[parent_object_id]
    INNER JOIN sys.columns col1 ON col1.[column_id] = parent_column_id AND col1.[object_id] = tab1.[object_id]
    INNER JOIN sys.tables tab2 ON tab2.[object_id] = fkc.[referenced_object_id]
    INNER JOIN sys.columns col2 ON col2.[column_id] = referenced_column_id AND col2.[object_id] = tab2.[object_id]
) f ON f.[table] = t.[TABLE_NAME] AND f.[column] = c.[COLUMN_NAME]
LEFT OUTER JOIN (
    SELECT OBJECT_NAME(ic.[OBJECT_ID]) AS [table],
            COL_NAME(ic.[OBJECT_ID], ic.[column_id]) AS [column]
    FROM sys.indexes AS i
    INNER JOIN sys.index_columns AS ic ON i.[OBJECT_ID] = ic.[OBJECT_ID] AND i.[index_id] = ic.[index_id]
    WHERE i.[is_primary_key] = 1
) p ON p.[table] = t.[TABLE_NAME] AND p.[column] = c.[COLUMN_NAME]
--WHERE c.[TABLE_NAME] IN ('TB_')
ORDER BY c.[TABLE_NAME]



2019년 9월 17일 화요일

DB - MSSQL - 일별 / 주별 / 월별 / 분기별 날짜 구분




[MSSQL]일별,주별,월별 통계


-- 일단위
Select DATEPART(dd, order_dt), count(order_no) From 주문테이블
group by DATEPART(dd, order_dt)
order by DATEPART(dd, order_dt)



-- 주 단위
Select DATEPART(ww, order_dt), count(order_no) From 주문테이블
group by DATEPART(ww, order_dt)
order by DATEPART(ww, order_dt)



-- 월단위
Select DATEPART(mm, order_dt), count(order_no) From 주문테이블
group by DATEPART(mm, order_dt)
order by DATEPART(mm, order_dt)



-- 년단위
Select DATEPART(yy, order_dt), count(order_no) From 주문테이블
group by DATEPART(yy, order_dt)
order by DATEPART(yy, order_dt)



--분기별
SELECT A.memyear,A.AA,SUM(A.CNT) AS CNT
FROM (
Select DATEPART(yy, regdate) as memyear,DATEPART(mm, regdate) as memmonth,  count(regdate) as cnt
,(CASE DATEPART(mm, regdate) WHEN '1' THEN '1' WHEN '2' THEN '1' WHEN '3' THEN '1'
WHEN '4' THEN '2' WHEN '5' THEN '2' WHEN '6' THEN '2'
WHEN '7' THEN '3' WHEN '8' THEN '3' WHEN '9' THEN '3'
WHEN '10' THEN '4'
WHEN '11' THEN '4'
WHEN '12' THEN '4' ELSE '0' END) AS AA
From SMEM01MEM
group by DATEPART(mm, regdate),DATEPART(yy, regdate)
--order by DATEPART(ww, regdate)
) A
group by A.memyear,A.AA
order by A.memyear,A.AA



2019년 4월 5일 금요일

DB - SQL Interview Questions & Answers




1. What is DBMS?
A Database Management System (DBMS) is a program that controls creation, maintenance and use of a database. DBMS can be termed as File Manager that manages data in a database rather than saving it in file systems.
2. What is RDBMS?
RDBMS stands for Relational Database Management System. RDBMS store the data into the collection of tables, which is related by common fields between the columns of the table. It also provides relational operators to manipulate the data stored into the tables.
Example: SQL Server.
3. What is SQL?
SQL stands for Structured Query Language , and it is used to communicate with the Database. This is a standard language used to perform tasks such as retrieval, updation, insertion and deletion of data from a database.
Standard SQL Commands are Select.
4. What is a Database?
Database is nothing but an organized form of data for easy access, storing, retrieval and managing of data. This is also known as structured form of data which can be accessed in many ways.
Example: School Management Database, Bank Management Database.
5. What are tables and Fields?
A table is a set of data that are organized in a model with Columns and Rows. Columns can be categorized as vertical, and Rows are horizontal. A table has specified number of column called fields but can have any number of rows which is called record.
Example:.
Table: Employee.
Field: Emp ID, Emp Name, Date of Birth.
Data: 201456, David, 11/15/1960.
6. What is a primary key?
A primary key is a combination of fields which uniquely specify a row. This is a special kind of unique key, and it has implicit NOT NULL constraint. It means, Primary key values cannot be NULL.
7. What is a unique key?
A Unique key constraint uniquely identified each record in the database. This provides uniqueness for the column or set of columns.
A Primary key constraint has automatic unique constraint defined on it. But not, in the case of Unique Key.
There can be many unique constraint defined per table, but only one Primary key constraint defined per table.
8. What is a foreign key?
A foreign key is one table which can be related to the primary key of another table. Relationship needs to be created between two tables by referencing foreign key with the primary key of another table.
9. What is a join?
This is a keyword used to query data from more tables based on the relationship between the fields of the tables. Keys play a major role when JOINs are used.
10. What are the types of join and explain each?
There are various types of join which can be used to retrieve data and it depends on the relationship between tables.
  • Inner Join.
Inner join return rows when there is at least one match of rows between the tables.
  • Right Join.
Right join return rows which are common between the tables and all rows of Right hand side table. Simply, it returns all the rows from the right hand side table even though there are no matches in the left hand side table.
  • Left Join.
Left join return rows which are common between the tables and all rows of Left hand side table. Simply, it returns all the rows from Left hand side table even though there are no matches in the Right hand side table.
  • Full Join.
Full join return rows when there are matching rows in any one of the tables. This means, it returns all the rows from the left hand side table and all the rows from the right hand side table.
11. What is normalization?
Normalization is the process of minimizing redundancy and dependency by organizing fields and table of a database. The main aim of Normalization is to add, delete or modify field that can be made in a single table.
12. What is Denormalization.
DeNormalization is a technique used to access the data from higher to lower normal forms of database. It is also process of introducing redundancy into a table by incorporating data from the related tables.
13. What are all the different normalizations?
The normal forms can be divided into 5 forms, and they are explained below -.
  • First Normal Form (1NF):.
This should remove all the duplicate columns from the table. Creation of tables for the related data and identification of unique columns.
  • Second Normal Form (2NF):.
Meeting all requirements of the first normal form. Placing the subsets of data in separate tables and Creation of relationships between the tables using primary keys.
  • Third Normal Form (3NF):.
This should meet all requirements of 2NF. Removing the columns which are not dependent on primary key constraints.
  • Fourth Normal Form (3NF):.
Meeting all the requirements of third normal form and it should not have multi- valued dependencies.
14. What is a View?
A view is a virtual table which consists of a subset of data contained in a table. Views are not virtually present, and it takes less space to store. View can have data of one or more tables combined, and it is depending on the relationship.
15. What is an Index?
An index is performance tuning method of allowing faster retrieval of records from the table. An index creates an entry for each value and it will be faster to retrieve data.
16. What are all the different types of indexes?
There are three types of indexes -.
  • Unique Index.
This indexing does not allow the field to have duplicate values if the column is unique indexed. Unique index can be applied automatically when primary key is defined.
  • Clustered Index.
This type of index reorders the physical order of the table and search based on the key values. Each table can have only one clustered index.
  • NonClustered Index.
NonClustered Index does not alter the physical order of the table and maintains logical order of data. Each table can have 999 nonclustered indexes.
17. What is a Cursor?
A database Cursor is a control which enables traversal over the rows or records in the table. This can be viewed as a pointer to one row in a set of rows. Cursor is very much useful for traversing such as retrieval, addition and removal of database records.
18. What is a relationship and what are they?
Database Relationship is defined as the connection between the tables in a database. There are various data basing relationships, and they are as follows:.
  • One to One Relationship.
  • One to Many Relationship.
  • Many to One Relationship.
  • Self-Referencing Relationship.
19. What is a query?
A DB query is a code written in order to get the information back from the database. Query can be designed in such a way that it matched with our expectation of the result set. Simply, a question to the Database.
20. What is subquery?
A subquery is a query within another query. The outer query is called as main query, and inner query is called subquery. SubQuery is always executed first, and the result of subquery is passed on to the main query.
21. What are the types of subquery?
There are two types of subquery – Correlated and Non-Correlated.
A correlated subquery cannot be considered as independent query, but it can refer the column in a table listed in the FROM the list of the main query.
A Non-Correlated sub query can be considered as independent query and the output of subquery are substituted in the main query.
22. What is a stored procedure?
Stored Procedure is a function consists of many SQL statement to access the database system. Several SQL statements are consolidated into a stored procedure and execute them whenever and wherever required.
23. What is a trigger?
A DB trigger is a code or programs that automatically execute with response to some event on a table or view in a database. Mainly, trigger helps to maintain the integrity of the database.
Example: When a new student is added to the student database, new records should be created in the related tables like Exam, Score and Attendance tables.
24. What is the difference between DELETE and TRUNCATE commands?
DELETE command is used to remove rows from the table, and WHERE clause can be used for conditional set of parameters. Commit and Rollback can be performed after delete statement.
TRUNCATE removes all rows from the table. Truncate operation cannot be rolled back.
25. What are local and global variables and their differences?
Local variables are the variables which can be used or exist inside the function. They are not known to the other functions and those variables cannot be referred or used. Variables can be created whenever that function is called.
Global variables are the variables which can be used or exist throughout the program. Same variable declared in global cannot be used in functions. Global variables cannot be created whenever that function is called.
26. What is a constraint?
Constraint can be used to specify the limit on the data type of table. Constraint can be specified while creating or altering the table statement. Sample of constraint are.
  • NOT NULL.
  • CHECK.
  • DEFAULT.
  • UNIQUE.
  • PRIMARY KEY.
  • FOREIGN KEY.
27. What is data Integrity?
Data Integrity defines the accuracy and consistency of data stored in a database. It can also define integrity constraints to enforce business rules on the data when it is entered into the application or database.
28. What is Auto Increment?
Auto increment keyword allows the user to create a unique number to be generated when a new record is inserted into the table. AUTO INCREMENT keyword can be used in Oracle and IDENTITY keyword can be used in SQL SERVER.
Mostly this keyword can be used whenever PRIMARY KEY is used.
29. What is the difference between Cluster and Non-Cluster Index?
Clustered index is used for easy retrieval of data from the database by altering the way that the records are stored. Database sorts out rows by the column which is set to be clustered index.
A nonclustered index does not alter the way it was stored but creates a complete separate object within the table. It point back to the original table rows after searching.
30. What is Datawarehouse?
Datawarehouse is a central repository of data from multiple sources of information. Those data are consolidated, transformed and made available for the mining and online processing. Warehouse data have a subset of data called Data Marts.
31. What is Self-Join?
Self-join is set to be query used to compare to itself. This is used to compare values in a column with other values in the same column in the same table. ALIAS ES can be used for the same table comparison.
32. What is Cross-Join?
Cross join defines as Cartesian product where number of rows in the first table multiplied by number of rows in the second table. If suppose, WHERE clause is used in cross join then the query will work like an INNER JOIN.
33. What is user defined functions?
User defined functions are the functions written to use that logic whenever required. It is not necessary to write the same logic several times. Instead, function can be called or executed whenever needed.
34. What are all types of user defined functions?
Three types of user defined functions are.
  • Scalar Functions.
  • Inline Table valued functions.
  • Multi statement valued functions.
Scalar returns unit, variant defined the return clause. Other two types return table as a return.
35. What is collation?
Collation is defined as set of rules that determine how character data can be sorted and compared. This can be used to compare A and, other language characters and also depends on the width of the characters.
ASCII value can be used to compare these character data.
36. What are all different types of collation sensitivity?
Following are different types of collation sensitivity -.
  • Case Sensitivity – A and a and B and b.
  • Accent Sensitivity.
  • Kana Sensitivity – Japanese Kana characters.
  • Width Sensitivity – Single byte character and double byte character.
37. Advantages and Disadvantages of Stored Procedure?
Stored procedure can be used as a modular programming – means create once, store and call for several times whenever required. This supports faster execution instead of executing multiple queries. This reduces network traffic and provides better security to the data.
Disadvantage is that it can be executed only in the Database and utilizes more memory in the database server.
38. What is Online Transaction Processing (OLTP)?
Online Transaction Processing (OLTP) manages transaction based applications which can be used for data entry, data retrieval and data processing. OLTP makes data management simple and efficient. Unlike OLAP systems goal of OLTP systems is serving real-time transactions.
Example – Bank Transactions on a daily basis.
39. What is CLAUSE?
SQL clause is defined to limit the result set by providing condition to the query. This usually filters some rows from the whole set of records.
Example – Query that has WHERE condition
Query that has HAVING condition.
40. What is recursive stored procedure?
A stored procedure which calls by itself until it reaches some boundary condition. This recursive function or procedure helps programmers to use the same set of code any number of times.
41. What is Union, minus and Interact commands?
UNION operator is used to combine the results of two tables, and it eliminates duplicate rows from the tables.
MINUS operator is used to return rows from the first query but not from the second query. Matching records of first and second query and other rows from the first query will be displayed as a result set.
INTERSECT operator is used to return rows returned by both the queries.
42. What is an ALIAS command?
ALIAS name can be given to a table or column. This alias name can be referred in WHERE clause to identify the table or column.
Example-.
Select st.StudentID, Ex.Result from student st, Exam as Ex where st.studentID = Ex. StudentID
Here, st refers to alias name for student table and Ex refers to alias name for exam table.
43. What is the difference between TRUNCATE and DROP statements?
TRUNCATE removes all the rows from the table, and it cannot be rolled back. DROP command removes a table from the database and operation cannot be rolled back.
44. What are aggregate and scalar functions?
Aggregate functions are used to evaluate mathematical calculation and return single values. This can be calculated from the columns in a table. Scalar functions return a single value based on the input value.
Example -.
Aggregate – max(), count - Calculated with respect to numeric.
Scalar – UCASE(), NOW() – Calculated with respect to strings.
45. How can you create an empty table from an existing table?
Example will be -.
Select * into studentcopy from student where 1=2
Here, we are copying student table to another table with the same structure with no rows copied.
46. How to fetch common records from two tables?
Common records result set can be achieved by -.
Select studentID from student. <strong>INTERSECT </strong> Select StudentID from Exam
47. How to fetch alternate records from a table?
Records can be fetched for both Odd and Even row numbers -.
To display even numbers-.
Select studentId from (Select rowno, studentId from student) where mod(rowno,2)=0
To display odd numbers-.
Select studentId from (Select rowno, studentId from student) where mod(rowno,2)=1
from (Select rowno, studentId from student) where mod(rowno,2)=1.[/sql]
48. How to select unique records from a table?
Select unique records from a table by using DISTINCT keyword.
Select DISTINCT StudentID, StudentName from Student.
49. What is the command used to fetch first 5 characters of the string?
There are many ways to fetch first 5 characters of the string -.
Select SUBSTRING(StudentName,1,5) as studentname from student
Select RIGHT(Studentname,5) as studentname from student
50. Which operator is used in query for pattern matching?
LIKE operator is used for pattern matching, and it can be used as -.
  1. % - Matches zero or more characters.
  2. _(Underscore) – Matching exactly one character.
Example -.
Select * from Student where studentname like 'a%'
Select * from Student where studentname like 'ami_'



MSSQL - Cursor vs Temp Table

#테이블 변수사용의 예 use pubs go declare @tmptable table (     nid int identity(1,1) not null,     title varchar (80) not null ) -- 테이블 변수 선언 inse...