'Etc'에 해당되는 글 115건

  1. Mongo DB 설치 (윈7)
  2. In which order does SQL Server process SQL statements
  3. DBA 101: Best Practices All DBAs Should Follow
  4. Mastering DBA Soft Skills 2
  5. NULL의 형태?
  6. TEST시 모든 변수 선언하지 말자. 상수값으로 대체 한다. 3
  7. 053. sc 명령을 이용한 서비스 설정
  8. single page or multi page allocate
  9. delete dml 을 ddl 로 고치기 (특수한 업무의 효율을 높이기 위해서 )
  10. 요즘 관심 사항

Mongo DB 설치 (윈7)


참고

http://www.iaji.net/how-to-install-mongodb-and-php-mongo-extension-on-windows-7.html#more-1318
http://www.mongodb.org/display/DOCS/Quickstart+Windows#QuickstartWindows-Learnmore
http://www.webiyo.com/2011/02/install-mongodb-service-on-windows-7.html 


Win7 몽고DB 설치
1. 몽고DB 최신 버젼을 다운로드(여기)
2. 다운로드한 파일을 C:\mongodb폴더에 압축 해제합니다.(쓰기 권한이 있는지 확인 필수)
3. 몽고 DB용 데이타 폴더를 생성합니다.


4. 몽고DB 실행  
MongDB는 포트로 27017 포트를 사용
데이타 디렉토리가 존재하지 않거나 쓰기 권한이 없을 때에는 서버는 시작되지 않는다
(c:\data\db)
 



Win7 몽고 DB 환경변수 설정

1. 내컴퓨터 > 속성 > 고급 시스템 설정
2. 고급 > 환경 변수
3. 시스템 변수 > Path


 4. 시스템 변수 편집
     C:\mongodb\bin
 


 
Mongo DB 서비스 설정
1. C:\mongodb\log 디렉토리 생성 후 log.txt 파일을생성합니다.
2. Command 명령어로 서비스를 생성합니다.(관리자 권한으로 실행)

c:\mongodb\bin>mongod.exe --bind_ip 127.0.0.1 --logpath c:\mongodb\log\log.txt --logappend --dbpath c:\data\db --directoryperdb --install
(서비스 제거, --install 대신에 --remove)
(서비스 제거, sc delete MongoDB)




설치 끝!!

 



'Etc' 카테고리의 다른 글

NOSQL - MongGo DB  (1) 2011.04.26
NoSQL 에 대한 블로그 포스트 모음  (0) 2011.04.18
In which order does SQL Server process SQL statements  (0) 2010.04.22
DBA 101: Best Practices All DBAs Should Follow  (0) 2009.10.28
Mastering DBA Soft Skills  (2) 2009.10.28

http://www.sqlhacks.com/FAQs/ProcessingLogic


SELECT DISTINCT TOP (list)
FROM (LeftTable)
(join type) JOIN (RightTable)
ON (condition])
WHERE (condition)
GROUP BY (list)
WITH (CUBE | ROLLUP)
HAVING (condition)
ORDER BY (list)

Evaluation order:

  1. FROM (LeftTable)
  2. ON (condition)
  3. (join type) JOIN (RightTable)
  4. WHERE (condition)
  5. GROUP BY (list)
  6. WITH (CUBE | ROLLUP)
  7. HAVING (condition)
  8. SELECT
  9. DISTINCT
  10. ORDER BY (list)
  11. TOP (list)
  • SQL first evaluate the FROM files.
  • Then the conditions of the FROMs.
  • Then how it will group/summaries...
  • Then finally the SELECT statement.

This means that everything has to be defined in the order of evaluation by SQL (ie: aliases, calculated fields...)

'Etc' 카테고리의 다른 글

NoSQL 에 대한 블로그 포스트 모음  (0) 2011.04.18
Mongo DB 설치 (윈7)  (0) 2011.03.15
DBA 101: Best Practices All DBAs Should Follow  (0) 2009.10.28
Mastering DBA Soft Skills  (2) 2009.10.28
NULL의 형태?  (0) 2009.06.29

Check & Verify
• Installing & Upgrading SQL Server
• General Server Configuration
• Memory Configuration
• User Data and Log File Management
• Tempdb Management
• Database Configuration Settings
• Configuring Jobs—General
• Create Index Rebuilding/Reorganize Job
• Create Data Corruption Detection Job
• Set Up Alerts for Critical Errors
• Security Basics
• Implement a Backup/Restore Strategy
• Create a Disaster Recovery Plan
• Test Everything

Tempdb Management
• Pre-size files so autogrowth doesn’t have to happen often
(8MB is default).
• Set autogrowth to avoid many growth spurts, use a fixed
amount that minimizes autogrowth use. (10% is default).
• If very active, locate it on its own volume.
• If very active, consider dividing the tempdb into multiple
physical files so that the number of files is about 50% to 100%
of the number of CPU cores your server has. Each physical file
must be the same size.

Database Configuration Settings
• Auto Create Statistics: On
• Auto Update Statistics: On
• Auto Shrink: Off
• Page Verify: Use Checksum (2005/2008), don’t turn off
• Autogrowth: Leave on. Use mainly for catching mistakes. File
growth should be managed manually. Use fixed amount that
minimizes autogrowth occurrences.
• Production databases should be set to FULL RECOVERY so
transaction log backups can be made.

Create Index Rebuilding/Reorganize Job
• Indexes need to be rebuilt or reorganized regularly to minimize fragmentation and reduce wasted space.

• Consider rebuilding an index if it is heavily fragmented (>30%). In Enterprise Edition, can perform online. If Standard Edition, consider it an off-line job. This automatically updates statistics, do you don’t need to do this again.

• Consider reorganizing an index if it is not heavily fragmented (>5% and <= 30%). This is an online operation and doesn’t use a lot of resources. You must update statistics afterwards, as this is not automatically done for you.

• Ideally, you should only rebuild or reorganize indexes that need it. Use sys.dm_db_index_physical_stats to  dentify what tables/indexes need to be rebuilt/reorganized.

Mastering DBA Soft Skills

 


Mastering soft skills is just as important as learning technical skills. Key skills include:

– People skills
– Teamwork skills
– Project management
– Leadership skills
– Time management
– Writing skills
– Speaking skills
– Knowledge of legal responsibilities

As a DBA (or developer), there are many related technical skills we need to master, and keep up with, including:

– Operating system
– Hardware (SANs, etc.)
– Clustering
– Virtualization
– Development technologies
– Tools and utilities

Choose one or more of the following specialty areas:

– DBA Administrator
– DBA Developer
– DBA High Availability/Disaster Recovery Specialist
– DBA Database Designer/Architect
– DBA Business Intelligence Specialist (Hot growth area)
– DBA SSIS Specialist
– DBA Reporting Services Specialist
– DBA Trainer
– DBA Consultant
– Among others

내가 Exceptional DBA가 되기 위해서 할것도 많다. ㅜ.ㅜ

NULL의 형태?


"값도 없으면서, 빈 것도 아니다" 라는 의미도 있고 다양하다. NULL이라는 것을 아직 가지지 않았다는 적극적인 의사표현이다.

알아야 할것.
  1. NULL과 모든 값들과의 연산은 NULL이다.
  2. NULL과 관련해서 비교하거나 연산을 하려면, 별도의 NULL관련 함수들을 사용해야만 한다.
  3. NULL의 비교 IS NULL, IS NOT NULL
  4. NULL의 함수들
    1. ISNULL
    2. Coalesce : 이중에 NULL이 아닌 값은 누굴까?
    3. NULLIF : 같은 값이면 NULL



SQL 서버는 NULL값을 특정한 비트맵으로 변경하여 데이터로 저장하고 있다. 이 덕분에 다른 데이터베이스와 다르게 NULL이 포함된 값도 인덱스에서 조회가 가능하다. 

2009.03.07 SQL Off-Study


USE AdventureWorks
GO
SELECT *
FROM HumanResources.EmployeePayHistory
WHERE EmployeeID = 24
GO
DECLARE @EmployeeID int
SET @EmployeeID = 24
SELECT *
FROM HumanResources.EmployeePayHistory
WHERE EmployeeID = @EmployeeID
GO

상수에 의한 실행계획을 확인한다.
왜냐, equal 검색은 변수로 받을 경우 10% data 가정으로 찾고, range seek는 15% 가정하고 진행한다.
그렇기 때문에 모든 테스트 및 실행계획 할 때에는 상수값을 이용하여 확인할 것..

2009.03.24

2009.04.07
위의 내용은 SQL2000/2005 튜닝 - 정원혁 저 P.288 참조
상수 폴딩(Constant folding) 이라고 한다.

쿼리 처리 과정
1. 구문 분석(parsing)
2. 표준화(Standardization)
3. 최적화(Optimization)
4. 컴파일(Compilation)
5. 실행(Execute)

최적화기는 통계 정보의 해당 행에 대한 빈도, 즉 분포도(Histogram)를 사용하여 해당 행이 몇%나 되는지 계산하고 각각 테이블 스캔, 인덱스 검색이라는 제대로된 플랜을 만들어 낸다.
하지만, 변수로 받아질 경우,,, 최적화기는 분포도(Histogram)을 사용하지 못하고, 단지 해당 테이블에서 임의의 값 하나를 가져올 경우에 해당하는 밀도를 판단 한다.  <<-- 아하,,,
그중,,,all density value를 확인하여 사용하게 되는데, 예 1.1392~


요건,,,, 내일 회사 가서 다시 테스트 해보자...

Sc.exe를 사용하여 Windows 서비스를 만드는 방법 http://support.microsoft.com/kb/251192/ko

SC 명령을 통한 서비스 제어 sample http://cupid4u.cafe24.com/tater2/entry/Server-Default-Setting?TSSESSION=3c307d512925485740830c916016dbb5

http://ibecky.tistory.com/tag/SC



도대체 sc 명령어가 머냐??
command 명령어를 이용하여 서비스를 시작하고 종료할 수 잇는 명령어 이군

인스턴스로 설치를 하셨다면 net start mssql$<인스턴스명> 식으로 시작과 정지가 가능합니다


sc config mssqlserver start= auto
sc config sqlserveragent start= auto

net start mssqlserver
net start sqlserveragent



SC 명령어

sc stop mssql$mssql2008
sc start mssql$mssql2008




sc는 서비스 관련 API를 실행할 수 있도록 만들어진 윈도우즈 내장 프로그램이다. 가능한 OS는 아래에 나열했다.

  • Microsoft Windows NT Server 4.0, Terminal Server Edition
  • Microsoft Windows 2000 Server
  • Microsoft Windows 2000 Advanced Server
  • Microsoft Windows 2000 Professional Edition
  • Microsoft Windows NT Server 3.51
  • Microsoft Windows NT Server 4.0 Standard Edition


    XP가 언급되지 않았는데 확인해 본 결과 XP에도 포함되어 있다. 아마 내가 XP 이전에 작성된 문서를 본 것 같다. 아쉽게도 VISTA에서는 정말로 빠진 듯 하다. WDF로 넘어오면서 철저한 보안검사 때문에 빠진듯 하다. 아무튼 서비스가 정상적으로 등록되어 있다면

    sc start 서비스이름

    또는

    net start 서비스이름

    을 이용해서 구동할 수가 있다. 난 습관적으로 net start를 이용하곤 하는데 타이핑면에서 sc가 효율적이므로 슬슬 케케묵은 습관은 버릴때가 되었다. 자, 이제 오늘의 핵심인 서비스를 등록하는 부분을 살펴보자. 일단 사용법을 살펴보기 위해서 sc create 라고 타이핑해봤다.

    Creates a service entry in the registry and Service Database.
    SYNTAX:
    sc create [service name] [binPath= ] <option1> <option2>...
    CREATE OPTIONS:
    NOTE: The option name includes the equal sign.
     type= <own|share|interact|kernel|filesys|rec>
           (default = own)
     start= <boot|system|auto|demand|disabled>
           (default = demand)
     error= <normal|severe|critical|ignore>
           (default = normal)
     binPath= <BinaryPathName>
     group= <LoadOrderGroup>
     tag= <yes|no>
     depend= <Dependencies(separated by / (forward slash))>
     obj= <AccountName|ObjectName>
           (default = LocalSystem)
     DisplayName= <display name>
     password= <password>

    이 보다 깔끔하게 잘 정리된 사용법도 없을 것이다. 실제 드라이버를 만들어서 등록하기 위해서 아래와 같이 타이핑했다.

    sc create Handle binPath="C:\Handle.sys" displayName="+_+ Win32 handle viewer" type=Kernle

    사용법대로 철자하나 틀리지 않게 잘 썼다고 생각하고 엔터를 눌렀지만 돌아오는것은 사용법에 관한 Echo뿐 ㅠ ㅠ
    무엇이 잘못 된 것일까? 난 sc 명령을 사용하는 사용자 권한 문제로 파악하고 administrator 권한으로 로그인하고 별의별 짓을
    다 했지만 결국 해결할 수가 없었다. 30분 정도의 웹 검색으로 알게 된 사.실!!!

    사용법을 잘 보시라! 옵션의 이퀄(=) 다음에 분명히!!!! 공백이 하나 존재한다!!!!!

    도움말과 사용법은 글자 하나 빠뜨리지 말고 꼼꼼하게! 세심하게 살핍시다. :(



  • showlogs , showenvironment, showlocator, showfru, consolehistory H/W 장애시 다섯개만 보내주면 썬이 해결해 주지여.. ㅋㅋㅋㅋ



    sc 명령어 = 하드웨어 관련

    2008/01/14 11:37

    복사 http://blog.naver.com/formidori/130026708927

    @ sc platfomr shell commands

     

    sc> help - 도움말

     

    ---------------------------------@정보확인--------------------------------

     

    history - 날짜 시간 커멘트히스토리 확인
    showrc - sc의 업타임 버전확인
    showdate - sc,도메인 time,date 확인
    showlogs - 현재 로깅 설정 확인
    showplatform - 플렛폼 환경설정 확인

    showboards - 각보드의 status와 assign 정보확인
    showcomponent - 컴퍼넌트리스트 확인
    showenvironment - status, temperature,voltage,fanspeed 등 환경확인
    showkeyswitch - keyswitch setting 확인

    showcodlicense - cod license 확인
    showcodlog - cod 로그 히스토리
    showcodusage - usage current cod license 확인


    [출처] sc 명령어|작성자



    ------------@ 시스템컨트롤러 셋업 ( 스페어 sc도 같은방식으로 구성해준다)----------

    sc> setupplatform - sc세업
    sc> reboot - 셋업후 재부팅 (꼭 실행할필욘없음)
    sc> showplatform - 셋업이 재대로 되었는지 확인한다
    sc> showboards - 보드의 상태를 확인
    sc> poweron all - 모든 보드를 파워온한다
    sc> showsc -v
    sc> showboards -p prom  - 모든 보드의 PROM 정보확인후
    sc> flashupdate -y -f ftp://root:passwd@108.2.1.187/112883-06 all rtos
    - PROM 이 낮다면 업데이트해준다
    sc> showdate  - 날짜를 확인후
    sc> setdate -t JST 011309002008.30 - 시간을 맞추어준다(예:2003년1월13일9시0분30초)

     

    ----------------------------------@ 도메인구성--------------------------------------

    sc> addboard -d a SB0 IB6 - 도메인A에 SB0 IB6 을 추가
    sc> console a - 도메인A로 접속
    A> setupdomain - 도메인셋업
    A> showdomain  - 셋업확인
    A> setdate -t GMT+9 011309002008.30 - 시간을 맞추어준다(예:2003년1월13일9시0분30초)
    A> setkeyswitch on - 도메인 on
    ok> boot cdrom - os설치 시작

    [출처] sc 셋팅|작성자



    은행 사이트 들어갔다가 나오면 어쩔수 없이 npkc*** 프로세스가 작동되었는데

    작업 관리자에 보면 이게 계속 서비스에서 활성화 되어있는게 소스만 차지하고 있습니다.

    이걸 없앨수는 없더군요. 그래서 찾아보다가 SC 명령어란게 있더군요. 제어하는 명령어 인데 정말 유용합니다.

    관련내용 링크입니다. http://ibecky.tistory.com/tag/SC

     

     

    이걸 활용하여 간단히 배치 파일 만들어 시작프로그램에 넣었어요.

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

    sc config npkcmsvc start= auto  -- 서비스 설정 (이건 이 서비스가 늦게 뜰 경우를 생각해서 )
    sc stop npkcmsvc   --- 서비스 중지
    sc config npkcmsvc start= disabled   ---- 서비스 사용안함

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

     

    위에 처럼 하면 윈도우 시작시 도스창이 보이게 되는데 이걸 안보이게 할수 있습니다.

     

    가령 npkcmsvc제한.vbs 라는 파일을 메모장으로 만들고

    ------------------------------------------------------------------------------
    Dim Shell

    Set Shell = WScript.CreateObject("WScript.Shell")

    Shell.run "sc config npkcmsvc start= auto", 0 ,true
    Shell.run "sc stop npkcmsvc", 0 ,true
    Shell.run "sc config npkcmsvc start= disabled", 0 ,true
    ------------------------------------------------------------------------------

    이렇게 만들어서 시작프로그램에 넣으면 끝.

     

    이렇게 하면 윈도우시작시 서비스가 자동으로 실행되고 정지한다음 사용안함 상태로 만듭니다.

     

    출처:http://blog.daum.net/toupto/6649817

     

    첨부파일 nprotect제한.vbs

    ↑ 시작프로그램에 넣어주고 윈도우 다시시작 합니다.

     

    첨부파일 sc_5893.pdf




     

    두개의 차이는 테이블의 사이즈에 따라서 다르다 또는 옵션 설정에 따라 다르다...


    FIX: tempdb 데이터베이스에 대한 동시성 강화
    http://support.microsoft.com/kb/328551/ko

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

    개체를 생성하는 동안 혼합 익스텐트 및 새 개체에 두(2) 페이지를 할당해야 합니다. 한 페이지는 IAM(Index Allocation Map)을 위한 것이고 두 번째 페이지는 개체의 첫 페이지를 위한 것입니다. SQL Server는 SGAM(Shared Global Allocation Map) 페이지를 사용하여 혼합 익스텐트를 추적합니다. 각 SGAM 페이지는 약 4GB의 데이터를 추적합니다.

    혼합 익스텐트에서 페이지 할당의 일환으로 SQL Server는 PFS(Page Free Space) 페이지를 검색하여 어떤 혼합 페이지를 할당할 수 있는지 확인해야 합니다. PFS 페이지는 모든 페이지에서 사용할 수 있는 여유 공간을 추적하고 각 PFS 페이지는 약 8000 페이지를 추적합니다. PFS 및 SGAM 페이지를 변경하기 위해 적절한 동기화가 유지되며 이를 통해 잠시 동안 다른 수정 작업을 막을 수 있습니다.

    SQL Server가 할당할 혼합 페이지를 검색할 때는 항상 동일한 파일과 SGAM 페이지에서 검색을 시작합니다. 따라서 여러 혼합 페이지 할당이 진행되는 경우 SGAM 페이지에서 상당한 경합이 발생하여 본 문서의 "현상" 절에서 설명하는 문제가 초래될 수 있습니다.

    참고 할당 취소 작업도 페이지를 수정해야 하므로 경합이 한층 더 증가할 수 있습니다.

    SQL Server에서 사용하는 여러 가지 할당 메커니즘(SGAM, GAM, PFS, IAM)에 대해 자세히 알아보려면 본 문서의 "참조" 절을 참조하십시오.

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


    추적 플래그 -T1118에서 경합을 줄이는 방식

    다음은 -T1118에서 경합을 줄이는 방식을 나열한 것입니다.
    • -T1118은 서버 범위 설정입니다.
    • SQL Server의 시작 매개 변수에 -T1118 추적 플래그를 포함하여 SQL Server가 재활용된 후에도 추적 플래그가 유효한 상태를 유지합니다.
    • -T1118은 서버에서 단일 페이지 할당을 거의 모두 제거합니다.
    • 대부분의 단일 페이지 할당을 해제함으로써 SGAM 페이지에서 경합을 줄입니다.
    • -T1118을 설정하면 추적 플래그 없이 개체의 첫 8 페이지에 대한 익스텐트에서 수행되는 단일 페이지 할당과 반대로 개체에 대해 한 번에 8 페이지(1 익스텐트)를 할당하는 GAM 페이지(예: 2:1:2)에서 거의 모든 새 할당이 수행됩니다.
    • IAM 페이지는 -T1118이 설정된 상태에서도 여전히 SGAM 페이지에서 단일 페이지 할당을 사용합니다. 그러나 핫픽스 8.00.0702와 결합하고 tempdb 데이터 파일을 늘리면 SGAM 페이지에서 경합이 줄어드는 효과가 있습니다. 공간 문제에 대해서는 본 문서의 "단점" 절을 참조하십시오

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

    1. SQL Server 2000 서비스 팩 3(SP3)을 실행하는 서버의 경우 핫픽스 8.00.0765 또는 최신 보안 수정 프로그램 8.00.0818을 적용합니다. SQL Server SP2를 실행하는 서버의 경우 핫픽스 8.00.0702를 적용합니다.

      이들 수정 프로그램은 다음 위치에서 확인할 수 있습니다.

      8.00.0765

      814916  (http://support.microsoft.com/kb/814916/ ) FIX: 필터링된 게시에 대한 병합 에이전트가 실패할 수 있다
      8.00.0818
      http://www.microsoft.com/korea/technet/security/bulletin/MS03-031.asp (http://www.microsoft.com/korea/technet/security/bulletin/MS03-031.asp)
      8.00.0702
      328551  (http://support.microsoft.com/kb/328551/ ) FIX: tempdb 데이터베이스에 대한 동시성 강화
    2. 추적 플래그 -T1118을 구현합니다.
    3. 프로세서 수와 동일하게 tempdb 데이터 파일 수를 늘리고 동일한 크기로 파일을 만듭니다. 자세한 내용은 "추가 정보" 절을 참조하십시오.

     


    http://cafe.naver.com/sqlmvp/371


    -- test 목적
    -- 5일간 데이터만 보관한다.
    -- delete dml 의 비효율을 보완하기 위한 방법

    use master
    go

    if exists (select * from master.dbo.sysdatabases where name ='split')
    begin
     alter database split set single_user with rollback immediate
     drop database split
    end
    go

    create database split
    go

    use split
    go


    -- 이하 실행 및 테스트
    -- manage table
    if object_id ('dbo.d_manage') is not null
    drop table dbo.d_manage
    go

    create table dbo.d_manage(type varchar(100), i_dt smalldatetime)
    go

    create unique clustered index cl_d_manage on d_manage(i_dt, type)
    go


    insert into dbo.d_manage values('day', '20081201')
    insert into dbo.d_manage values('day', '20081202')
    insert into dbo.d_manage values('day', '20081203')
    insert into dbo.d_manage values('day', '20081204')
    insert into dbo.d_manage values('day', '20081205')
    go

    if object_id ('dbo.d_20081201') is not null
    begin
     drop table dbo.d_20081201
     drop table dbo.d_20081202
     drop table dbo.d_20081203
     drop table dbo.d_20081204
     drop table dbo.d_20081205
    end
     
    -- manage target table
    create table dbo.d_20081201(clubid varchar(100) not null, i_dt smalldatetime  not null check (i_dt = '20081201'), type varchar(100) not null, value varchar(100) not null)
    create table dbo.d_20081202(clubid varchar(100) not null, i_dt smalldatetime  not null check (i_dt = '20081202'), type varchar(100) not null, value varchar(100) not null)
    create table dbo.d_20081203(clubid varchar(100) not null, i_dt smalldatetime  not null check (i_dt = '20081203'), type varchar(100) not null, value varchar(100) not null)
    create table dbo.d_20081204(clubid varchar(100) not null, i_dt smalldatetime  not null check (i_dt = '20081204'), type varchar(100) not null, value varchar(100) not null)
    create table dbo.d_20081205(clubid varchar(100) not null, i_dt smalldatetime  not null check (i_dt = '20081205'), type varchar(100) not null, value varchar(100) not null)
    go

    -- test data 입력
    set nocount on
    insert into dbo.d_20081201 values ('1', '20081201', 'a', rand() * 10)
    insert into dbo.d_20081201 values ('2', '20081201', 'a', rand() * 10)
    insert into dbo.d_20081201 values ('1', '20081201', 'b', rand() * 10)
    insert into dbo.d_20081201 values ('2', '20081201', 'b', rand() * 10)

    insert into dbo.d_20081202 values ('1', '20081202', 'a', rand() * 10)
    insert into dbo.d_20081202 values ('2', '20081202', 'a', rand() * 10)
    insert into dbo.d_20081202 values ('1', '20081202', 'b', rand() * 10)
    insert into dbo.d_20081202 values ('2', '20081202', 'b', rand() * 10)

    insert into dbo.d_20081203 values ('1', '20081203', 'a', rand() * 10)
    insert into dbo.d_20081203 values ('2', '20081203', 'a', rand() * 10)
    insert into dbo.d_20081203 values ('1', '20081203', 'b', rand() * 10)
    insert into dbo.d_20081203 values ('2', '20081203', 'b', rand() * 10)

    insert into dbo.d_20081204 values ('1', '20081204', 'a', rand() * 10)
    insert into dbo.d_20081204 values ('1', '20081205', 'a', rand() * 10)
    insert into dbo.d_20081204 values ('2', '20081204', 'a', rand() * 10)
    insert into dbo.d_20081204 values ('1', '20081204', 'b', rand() * 10)
    insert into dbo.d_20081204 values ('2', '20081204', 'b', rand() * 10)

    insert into dbo.d_20081205 values ('1', '20081205', 'a', rand() * 10)
    insert into dbo.d_20081205 values ('2', '20081205', 'a', rand() * 10)
    insert into dbo.d_20081205 values ('1', '20081205', 'b', rand() * 10)
    insert into dbo.d_20081205 values ('2', '20081205', 'b', rand() * 10)
    go

    create unique clustered index cl_d_20081201 on d_20081201 (clubid, type, i_dt)
    create unique clustered index cl_d_20081202 on d_20081202 (clubid, type, i_dt)
    create unique clustered index cl_d_20081203 on d_20081203 (clubid, type, i_dt)
    create unique clustered index cl_d_20081204 on d_20081204 (clubid, type, i_dt)
    create unique clustered index cl_d_20081205 on d_20081205 (clubid, type, i_dt)
    go


    create view d
    as
      select * from dbo.d_20081201
    union all select * from dbo.d_20081202
    union all select * from dbo.d_20081203
    union all select * from dbo.d_20081204
    union all select * from dbo.d_20081205
    go

    -- 유저 데이터

    set statistics io on
    set statistics profile on

    set statistics io off
    set statistics profile off

    -- #################################################################################
    -- 원하는 쿼리 (원하는 성능이 나오는가?  : OK 해당 테이블만 정확히 억세스 한다.)
    -- #################################################################################
    select * from dbo.d where i_dt = cast('20081204' as smalldatetime) and type ='a' and clubid = '1'

    sp_helptext 'dbo.d '

    -- 결과
    -- 1 2008-12-04 00:00:00 a 8.14244

    -- 실행계획
    -- rows executes stmttext
    1 1 select * from dbo.d where i_dt = cast('20081204' as smalldatetime) and type ='a' and clubid = '1'    -- 결과   -- 1 2008-12-04 00:00:00 a 8.14244    -- 실행계획   -- rows executes stmttext  -- 1 1 select * from d where i_dt = cast('20081204' as smalldatetime) an
    1 1   |--Compute Scalar(DEFINE:([d_20081204].[clubid]=[d_20081204].[clubid], [d_20081204].[i_dt]=[d_20081204].[i_dt], [d_20081204].[type]=[d_20081204].[type], [d_20081204].[value]=[d_20081204].[value]))
    1 1        |--Clustered Index Seek(OBJECT:([split].[dbo].[d_20081204].[cl_d_20081204]), SEEK:([d_20081204].[clubid]='1' AND [d_20081204].[type]='a') ORDERED FORWARD)
    -- #################################################################################
    -- #################################################################################


    -- 아래 프로시저를 이용해 동적으로 view 를 만들어 줘야 한다.
    --1 batch 작업으로 일간 batch 작업을 시작 한다.
    -- 오늘은 20081206 이라고 가정한다.

    -- 호출시 테이블을 만들어 주는 프로시저
    go

    if object_id('dbo.usp_d_maketable') is not null
    drop proc dbo.usp_d_maketable
    go

    create proc dbo.usp_d_maketable
    (@adddate smalldatetime)
    as

    declare    @sql varchar(8000)
      , @adddatechar char(8)

    set @adddatechar = convert(char(8), @adddate, 112)
    select @adddatechar

    -- 이중 실행에 따른 오류 처리
    if exists( SELECT *
       FROM sysobjects
       where name = 'd_'+ @adddatechar )
    begin
     set @sql = 'drop table dbo.d_'+ @adddatechar
     exec (@sql)
    end


    set @sql = 'create table dbo.d_'+ @adddatechar +' (clubid varchar(100) not null, i_dt smalldatetime not null check (i_dt = '''+@adddatechar+'''), type varchar(100) not null, value varchar(100) not null)'
    exec (@sql)
    go

    -- 호출시 인덱스를 만들어 주는 프로시저
    if object_id('dbo.usp_d_makeindex') is not null
    drop proc dbo.usp_d_makeindex
    go

    create proc dbo.usp_d_makeindex
    (@adddate smalldatetime)
    as

    declare    @sql varchar(8000)
      , @adddatechar char(8)

    set @adddatechar = convert(char(8), @adddate, 112)
    select @adddatechar

    set @sql = 'create unique clustered index cl_d_'+ @adddatechar +' on d_'+ @adddatechar +' (clubid, i_dt, type)'
    exec (@sql)
    go

    -- 호출시 view 를 변경시켜줄 프로시저

    if object_id('dbo.usp_d_change_view') is not null
    drop proc dbo.usp_d_change_view
    go

    create proc dbo.usp_d_change_view
    (
      @addDate smalldatetime
    , @type varchar(100)
    , @cutOffDay int
    )
    as

    declare    @viewheader varchar(8000)
      , @viewbody varchar(8000)
      , @errStatus int

    select @viewheader ='' , @viewbody =''

    if not exists (select * from dbo.d_manage where type = @type and i_dt = @addDate)
     insert into d_manage values (@type , @adddate)

    set @viewheader =
    '
    alter view d
    as
    '
    select @viewbody = @viewbody + 'union all select * from dbo.d_'+ convert(char(8), i_dt, 112) + ' ' + char(13) + char(10)
    from dbo.d_manage
    where i_dt > dateadd(dd, @cutOffDay * -1 , @addDate) and type = @type

    select @viewbody = stuff(@viewbody, 1,10, '')

    exec (@viewheader + @viewbody)
    set @errStatus = @@error

    if @errStatus <> 0
     raiserror ('aa',15,1)
    else
     delete from dbo.d_manage
     where
       i_dt <= dateadd(dd, @cutOffDay * -1 , @addDate)
      and type = @type
    go

     

    set statistics profile off
    set statistics io off
    go

     

    -- 실제 작업

    -- 웹에서 테이블 생성 프로시저 호출
    exec dbo.usp_d_maketable '20081206'
    go

    -- 해당 테이블을 대상으로 하둡엔 리듀스 프레임 워크에서 데이터 밀어넣기
    -- 가상 데이터 삽입
    insert into dbo.d_20081206 values ('1', '20081206', 'a', rand() * 10)
    insert into dbo.d_20081206 values ('2', '20081206', 'a', rand() * 10)
    insert into dbo.d_20081206 values ('1', '20081206', 'b', rand() * 10)
    insert into dbo.d_20081206 values ('2', '20081206', 'b', rand() * 10)
    go

    -- 데이터 삽입과 인덱스 생성을 더 빠르게 하기위해 인덱스를 나중에 생성
    exec dbo.usp_d_makeindex '20081206'
    go

    -- 동적 SQL 을 이용해서 view 를 고쳐줌
    exec dbo.usp_d_change_view '20081206', 'day', 5
    go

    -- 과거 비효율 적으로 하나의 테이블에서 기간에 해당하는 테이블을 set rowcount 1000 delete d where i_dt < 날짜
    -- 형식으로 지우면서 2시간 ~ 3시간을 소모함

    -- 과거 테이블 drop
    -- 0초
    drop table dbo.d_20081201
    go


    exec sp_helptext d

    -- 결과
    -------------------------------------
    -- CREATE view d 
    -- as 
    -- select * from dbo.d_20081202  
    -- union all select * from dbo.d_20081203  
    -- union all select * from dbo.d_20081204  
    -- union all select * from dbo.d_20081205  
    -- union all select * from dbo.d_20081206  

     

    -- 실제 작업 test 2
    exec dbo.usp_d_maketable '20081207'
    go
    insert into dbo.d_20081207 values ('1', '20081207', 'a', rand() * 10)
    insert into dbo.d_20081207 values ('2', '20081207', 'a', rand() * 10)
    insert into dbo.d_20081207 values ('1', '20081207', 'b', rand() * 10)
    insert into dbo.d_20081207 values ('2', '20081207', 'b', rand() * 10)
    go
    exec dbo.usp_d_makeindex '20081207'
    go
    exec dbo.usp_d_change_view '20081207', 'day', 5
    go
    drop table dbo.d_20081202
    go

    sp_helptext d
    go


    select * from dbo.d_manage
    go
    -- type    i_dt                                                  
    -- ----- -----------------
    -- day 2008-12-03 00:00:00
    -- day 2008-12-04 00:00:00
    -- day 2008-12-05 00:00:00
    -- day 2008-12-06 00:00:00
    -- day 2008-12-07 00:00:00

    select * from dbo.d
    go
    [출처] delete dml 을 ddl 로 고치기 (특수한 업무의 효율을 높이기 위해서 ) (sqlmvp) |작성자 왕눈봄맘


     

    요즘 관심 사항

    SSRS, SSAS이다..특히나 SSAS쪽,,회사 업무에서 SSAS 서비스를 이용하여 BI 프로젝트를 개발 해보려고 한다.
    아.. 할것도 많고, 공부할 것도 많고..

    *.. 참고 링크..

    http://everybi.officetutor.org/category/SQL%20분석%20서비스