'SQL Server 2005'에 해당되는 글 50건

  1. DMV
  2. 유용한 DMV
  3. 업데이트 비용에 대한 고찰
  4. SQL의 SHFT 비트 연산
  5. SQL Server, SANs and Virtualisation
  6. The sqlcmd utility in SQL Server
  7. DB의 Collation
  8. 인덱스 사용중인 상태 체크
  9. 사용하지 않은 인덱스 찾기
  10. 데이타베이스 샘플 사이트

DMV

--> 정리하자..

응용 프로그램 성능 최적화를 위한 숨겨진 데이터 찾기
http://msdn.microsoft.com/ko-kr/magazine/cc135978.aspx#S1

4.0 Useful Queries on DMV’s to understand Plan Cache Behavior

http://blogs.msdn.com/sqlprogrammability/archive/2007/01/23/4-0-useful-queries-on-dmv-s-to-understand-plan-cache-behavior.aspx


1. Top SPs By Execution Count 
   얼마나 자주 sp를 호출하고,,,,, 평균 실행시간 및 캐쉬에 존재하였던 시간까지 모두 체크 가능하다..

-- Ver SQL2005
SELECT
TOP (100) qt.text AS 'SP Name', qs.execution_count AS 'Execution Count', 

qs.execution_count/DATEDIFF(Second, qs.creation_time, GetDate()) AS 'Calls/Second',

qs.total_worker_time/qs.execution_count AS 'AvgWorkerTime',

qs.total_worker_time AS 'TotalWorkerTime',

qs.total_elapsed_time/qs.execution_count AS 'AvgElapsedTime',

qs.max_logical_reads, qs.max_logical_writes, qs.total_physical_reads,

DATEDIFF(Minute, qs.creation_time, GetDate()) AS 'Age in Cache'

FROM sys.dm_exec_query_stats AS qs

CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS qt
WHERE qt.dbid = db_id() -- Filter by current database

ORDER BY qs.execution_count DESC
GO

-- Ver SQL2008

SELECT TOP (100) p.name AS 'SP Name', qs.execution_count,

ISNULL(qs.execution_count/DATEDIFF(Second, qs.cached_time, GetDate()), 0) AS 'Calls/Second',

qs.total_worker_time/qs.execution_count AS 'AvgWorkerTime', qs.total_worker_time AS 'TotalWorkerTime', 

qs.total_elapsed_time, qs.total_elapsed_time/qs.execution_count AS 'avg_elapsed_time', qs.last_elapsed_time,

qs.cached_time, qs.last_execution_time

FROM sys.procedures AS p

INNER JOIN sys.dm_exec_procedure_stats AS qs

ON p.object_id = qs.object_id

ORDER BY qs.execution_count DESC;




'SQL Server 2005' 카테고리의 다른 글

XML execution plans out as SQLPlan files  (0) 2009.03.24
sp_depends  (0) 2009.03.13
유용한 DMV  (0) 2009.03.04
업데이트 비용에 대한 고찰  (0) 2009.02.04
SQL의 SHFT 비트 연산  (0) 2009.01.13

유용한 DMV


으앙 ㅜ...ㅜ.
많이 달라졌다...

http://glennberrysqlperformance.spaces.live.com/blog/cns!45041418ECCAA960!1129.entry?wa=wsignin1.0&sa=974308588


응용 프로그램 성능 최적화를 위한 숨겨진 데이터 찾기
http://msdn.microsoft.com/ko-kr/magazine/cc135978.aspx#S1



SQL2008
sys.dm_exec_procedure_stats DMV that was added in SQL Server 2008

    -- Top SPs By Execution Count (SQL 2008)
    SELECT TOP (100) p.name AS 'SP Name', qs.execution_count,
    ISNULL(qs.execution_count/DATEDIFF(Second, qs.cached_time, GetDate()), 0) AS 'Calls/Second',
    qs.total_worker_time/qs.execution_count AS 'AvgWorkerTime', qs.total_worker_time AS 'TotalWorkerTime',  
    qs.total_elapsed_time, qs.total_elapsed_time/qs.execution_count AS 'avg_elapsed_time', qs.last_elapsed_time,
    qs.cached_time, qs.last_execution_time
    FROM sys.procedures AS p
    INNER JOIN sys.dm_exec_procedure_stats AS qs
    ON p.object_id = qs.object_id
    ORDER BY qs.execution_count DESC;
    
    -- Top SPs By Execution Count (SQL 2005)
    SELECT TOP (100) qt.text AS 'SP Name', qs.execution_count AS 'Execution Count',  
    qs.execution_count/DATEDIFF(Second, qs.creation_time, GetDate()) AS 'Calls/Second',
    qs.total_worker_time/qs.execution_count AS 'AvgWorkerTime',
    qs.total_worker_time AS 'TotalWorkerTime',
    qs.total_elapsed_time/qs.execution_count AS 'AvgElapsedTime',
    qs.max_logical_reads, qs.max_logical_writes, qs.total_physical_reads, 
    DATEDIFF(Minute, qs.creation_time, GetDate()) AS 'Age in Cache'
    FROM sys.dm_exec_query_stats AS qs
    CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS qt
    WHERE qt.dbid = db_id() -- Filter by current database
    ORDER BY qs.execution_count DESC
Technorati Tags:


'SQL Server 2005' 카테고리의 다른 글

sp_depends  (0) 2009.03.13
DMV  (0) 2009.03.09
업데이트 비용에 대한 고찰  (0) 2009.02.04
SQL의 SHFT 비트 연산  (0) 2009.01.13
SQL Server, SANs and Virtualisation  (0) 2009.01.09
http://kuaaan.tistory.com/29
http://support.microsoft.com/kb/832524


우리가 프로시져를 쓸 때 다음과 같은 구문을 자주 사용한다.

IF ((SELECT COUNT(*) FROM TEST_TAB WHERE STATUS = 'S') > 0)
     UPDATE TEST_TAB      SET STATUS = 'R'     WHERE STATUS = 'S'

위의 구분은 업데이트 대상이 존재하는지 먼저 SELECT해 보고,
대상이 있을 경우에만 UPDATE 한다는 뜻이다.
그렇다면, 왜 SELECT 테스트를 먼저 수행하는 것이 바로 UPDATE부터 수행하는 것보다 비용이 적을까?

(위의 예에서 테스트 대상 테이블은 26,000개의 레코드가 들어있었다.)
업데이트 대상이 존재할 경우, SELECT와 UPDATE를 둘 다 해야 하기 때문에
무조건 UPDATE부터 하는 것보다 분명히 더 비용이 비쌀 것으로 예상된다.

그렇다면... 업데이트 대상이 존재하지 않을 경우는 어떨까?
SELECT를 함으로서 UPDATE를 해보지 않아도 되기 때문에 더 적은 비용이 드는 걸까?

SELECT COUNT(*) FROM IP_TEST_TAB    WHERE STATUS = 'S' -- 1
UPDATE TEST_TAB   SET STATUS = 'R'     WHERE STATUS = 'S' -- 2

STATUS 컬럼이 'S'인 레코드가 한개도 없는 (즉, 업데이트 대상이 0개인) 상황을 만들어 놓고 위의 두가지 해 보았다. 프로필러에 나타난 결과는 다음과 같다.

1번 SELECT 문 : CPU(235), READ(1761), WRITE(0), DURATION(236)
2번 UPDATE 문 : CPU(0), READ(1186), WRITE(0), DURATION(16)

즉, 대상 데이터가 한개도 없는 경우에도 바로 UPDATE부터 실행시키는 것이 훨씬 비용이 적다는 것이다.

그렇다면, SELECT를 해서 UPDATE할 데이터가 있는지 체크해보지 않고 직접 UPDATE부터 하는 것이 더 좋은 방법일까??
아래의 테스트를 해 보자.
-- 세션 1, 2에서 아래의 SQL을 순서대로 실행
BEGIN TRAN
UPDATE TEST_TAB  SET STATUS = 'R' WHERE STATUS = 'S'
STATUS 컬럼을 모두 'R'로 변경한 상태에서 위의 SQL을 두 세션에서 순차적으로 실행시켜보자. 나중에 실행된 세션에서 LOCK이 걸리는가? 테스트해보면 LOCK이 걸리지는 않는 것을 알 수 있다.

UPDATE문을 실행시킬 때는 EXCLUSIVE LOCK이 걸린다. 즉, UPDATE문은 동시에 두개가 실행될 수 없다는 뜻이다. 그런데, 위의 테스트를 통해 LOCK 이 걸리는 것은 실제 변경되는 RECORD가 발생할 때 부터라는 것을 알 수 있었다. 요약하면, "UPDATE문을 실행했더라도 WHERE에 의해 영향을 받는 ROWS가 없는 경우는 LOCK이 걸리지 않는다."

상기 테스트를 종합해 볼 때... 아래와 같은 결론을 내릴 수 있다.

1. 어떤 경우에도  업데이트 전에 SELECT 테스트를 수행하는 것이 비용이 더 비싸다.
2. SELECT 테스트 없이 직접 UPDATE를 날리더라도 변경 대상 레코드가 없는 경우에는 EXCLUSIVE LOCK이 걸리지 않는다.
※ 따라서 SELECT 테스트 없이 직접 UPDATE부터 날리는 것이 더 낫다.

'SQL Server 2005' 카테고리의 다른 글

DMV  (0) 2009.03.09
유용한 DMV  (0) 2009.03.04
SQL의 SHFT 비트 연산  (0) 2009.01.13
SQL Server, SANs and Virtualisation  (0) 2009.01.09
The sqlcmd utility in SQL Server  (0) 2009.01.08

SQL의 SHFT 비트 연산

'SQL Server 2005' 카테고리의 다른 글

유용한 DMV  (0) 2009.03.04
업데이트 비용에 대한 고찰  (0) 2009.02.04
SQL Server, SANs and Virtualisation  (0) 2009.01.09
The sqlcmd utility in SQL Server  (0) 2009.01.08
DB의 Collation  (0) 2009.01.07
데이타베이스도 SAN Storage Platform으로 바뀌고 있다.. 어떠한 형식일까??

관련 링크
http://www.sqlservercentral.com/articles/SAN/65101/

SQL Server, SANs and Virtualisation

By Perry Whittle, 2009/01/08

Total article views: 5144 | Views in the last 30 days: 5144

SAN's and virtual platforms are fast becoming the norm for most companies\authorities now. This is all well and good for those that have interaction with these technologies and understand them, but what about the DBA. After all, if his\her SQL server will be connecting to backend SAN storage, they still need to understand a little about what it does. This is even more so if it's also a virtual machine. This article will give you some basics on how these things affect your database instance.

Let's start by breaking down the SAN,

What is a SAN?

Storage Area Networks basically consist of racks of disks connected by switches. The disks are "sliced" up into arrays called "LUN's". The switches used are not ordinary switches, they are fibre channel units supporting specialized protocols (lately FC-IP).

But why does the admin always refer to it as the fabric?

The "Fabric" is the term used to describe the high speed fibre channel network which comprises the SAN. This network consists of fibre channel switches, fibre optic cables and host bus adaptors (HBA's). Some older SAN technologies use hubs instead of switches, but these are now rare. The network configuration is usually automatic in that each switch registers a devices WWN when plugged into one of its ports. Each device has its own WWN which is a 64 bit unique ID (sort of like a MAC address but longer). This WWN is registered on the internal routing table and essentially builds a map. LUN's can be zoned to provide secure access between given ports. At the server end sits the HBA, an HBA is a plug in card much like a NIC and most have dual port capability, the fibre optic cable plugs into these ports. All these components link together and essentially present the storage as though it were locally attached.

How does it provide failover?

Multiple fabrics are usually employed to multi home devices to the disk storage. The diagram below shows a basic fabric configuration.

Although a little crude you should get the basic idea. Note the multi homing between the HBA's and the switches to provide a fail over path at any point. I have depicted SQL Server1 and SQL Server2 in the diagram above but these could quite easily be ESX hosts with virtual machines running inside them. Obviously the more devices you add (HBA's and switches), the more links you create to provide multi homed redundancy, and the larger they get the more complex they usually become.

In our scenario each HBA and switch are linked to multiple partners, Perimeter Switch1 and Core Switch1 make up Fabric1. Perimeter Switch2 and Core Switch2 make up Fabric2, so even with a core switch and a server HBA failure your server still has a path through to the storage. Another reason for this is, it allows a whole fabric to be taken offline and repaired\administered\etc without affecting storage access. Currently speeds of 2-4 Gbps are supported, but these speeds are ever increasing. For all their complexity SAN's are essentially, no different to ethernet networks (well maybe just a little).

So what is virtualization?

Modern virtualization technologies (HyperVisors) are merely a software layer which shares common hardware components among software based machines. They all work very differently, so it's best to clear this up from the start.

During a some of my previous scoping projects, a vendor has indicated to me that they didn't support their software on VMWare virtual machines as some of their customers had tried this and encountered performance problems. I became suspicious and asked the vendor which platform the customers had used, it turned out (much as i expected) they were using VMWare Server.

Now, don't get me wrong this product and Microsoft Virtual Server 2005 Enterprise are both ideal entry level virtualization platforms but should not be used in anger for a product such as a full blown GIS system or SQL\Exchange server. Having said that, I did have a 2 node SQL2005 cluster running on a laptop under MS VS2005 Enterprise. The laptop only died when I booted up the 3rd VM which was a Windows 2008 server (Beta) :-) , funny that!

The premium product currently on the market is VMWare's VI3 which incorporates ESX server 3.x, this host platform is extremely powerful and works quite differently to the previously mentioned products. The VI uses a management server which uses either a SQL or Oracle back end RDBMS. This is used to track\configure the entities in the virtual infrastructure.

The heart of the ESX server is the VMKernel (yes its a UNIX machine at heart), which is originally based on the Redhat 2.4.x kernel. It is totally stripped down and then rebuilt by the VMWare engineers. The VMWare kernel directly executes CPU code where ever possible except for special\privileged instructions, these use a process called binary translation, which interrupts the binary machine instructions and then re compiles them before sending them on to the virtual machine. The direct instruction execution affords the hypervisor superior performance as it does not emulate any instruction set, but can cause problems when moving VM's between hosts with disparate hardware (different CPUs specifically). When designing your virtual infrastructure it is best to decide on uniform hardware for the hosts from the outset to try and alleviate any problems that may arise as a result of different hardware (in other words don't buy 3 hosts with AMD Opteron and one with Intel Xeon).

Each virtual machine runs in its own memory\process space, so there is no danger of machines crossing address spaces. The infrastructure uses a .NET client which allows full management of the system including configuring storage, virtual machines, networking, etc. Shown below is a screenshot of the VMWare Virtual Infrastructure Client for a configured VI3 system. Note the storage LUN's under datastores.

The HBA's are installed to each ESXHOST and the disk stores; storage LUN's are configured using the SAN management software and presented to the virtual infrastructure via the HBAs. VI3 has 3 unique options "HA", "DRS" and "VMotion". "VMotion" is the proprietary technology VMWare use to migrate a VM from one host to another while running live. "VMotion" uses a special private network (at least 1 Gbps configured on each host) which passes the VM configuration details and memory footprint (unencrypted, hence the high speed private network) between hosts. "HA" is the high availability option which allows VM's to be automatically resumed on another partner host should the original host fail for some reason. HA uses a heart beat technology (again over a private network) and detection of a failure initiates restart on another host. "DRS" is the process of distributing VM's across hosts to relieve memory and CPU pressures, this uses resource pools and works in conjunction with VMotion. With resource pools it is possible to group VM's and throttle them accordingly.

With virtualization and SAN's fast becoming cheaper and popular there is more of a requirement for the DBA to understand these technologies. Many organizations world wide are seeing a lot of success vitalizing SQL servers, exchange servers, file servers, domain controllers and even software firewalls. Reducing datacentre sizes and power consumption are primary goals and also contribute heavily to streamlined corporate DR processes, after all if all your mission critical servers are VM's on one host then DR becomes easier and more manageable. There are many documents available on the Internet detailing Virtualization platforms and SAN topologies. For VMWare links go to

'SQL Server 2005' 카테고리의 다른 글

업데이트 비용에 대한 고찰  (0) 2009.02.04
SQL의 SHFT 비트 연산  (0) 2009.01.13
The sqlcmd utility in SQL Server  (0) 2009.01.08
DB의 Collation  (0) 2009.01.07
인덱스 사용중인 상태 체크  (0) 2009.01.07


sqlcmd -S server01\SqlSrv2008
sqlcmd -S server01\SqlSrv2008 -d AdventureWorks2008

 Syntax
sqlcmd 
[{ { -U login_id [ -P password ] } | –E trusted connection }] 
[ -z new password ] [ -Z new password and exit]
[ -S server_name [ \ instance_name ] ] [ -H wksta_name ] [ -d db_name ]
[ -l login time_out ] [ -A dedicated admin connection ] 
[ -i input_file ] [ -o output_file ]
[ -f < codepage > | i: < codepage > [ < , o: < codepage > ] ]
[ -u unicode output ] [ -r [ 0 | 1 ] msgs to stderr ] 
[ -R use client regional settings ]
[ -q "cmdline query" ] [ -Q "cmdline query" and exit ] 
[ -e echo input ] [ -t query time_out ] 
[ -I enable Quoted Identifiers ] 
[ -v var = "value"...] [ -x disable variable substitution ]
[ -h headers ][ -s col_separator ] [ -w column_width ] 
[ -W remove trailing spaces ]
[ -k [ 1 | 2 ] remove[replace] control characters ] 
[ -y display_width ] [-Y display_width ]
[ -b on error batch abort ] [ -V severitylevel ] [ -m error_level ] 
[ -a packet_size ][ -c cmd_end ] 
[ -L [ c ] list servers[clean output] ] 
[ -p [ 1 ] print statistics[colon format]] 
[ -X [ 1 ] ] disable commands, startup script, enviroment variables [and exit] 
[ -? show syntax summary ]
 


SELECT LastName
FROM Sales.vSalesPerson
ORDER BY LastName
GO

Running sqlcmd commands
In addition to running Transact-SQL statements in interactive mode, you can also run sqlcmd commands. The commands let you perform actions that cannot be performed by using Transact-SQL. For example, you can use sqlcmd commands to connect to a specific instance of SQL Server or to send query results to a text file. The following code demonstrates how you can use sqlcmd commands along with Transact-SQL in interactive mode:

:Connect server01\SqlSrv2008
:Out C:\Data\SqlCmdOutput.txt
USE AdventureWorks2008
GO
SELECT LastName
FROM Sales.vSalesPerson
ORDER BY LastName
GO
:EXIT


sqlcmd -d AdventureWorks -Q "SELECT LastName FROM Sales.vSalesPerson"

-- 실행 결과 OUTPUT
sqlcmd -i C:\Data\SqlCmdInput.sql -o C:\Data\SqlCmdOutput.txt –u


!!del C:\Data\SqlCmdOutput.txt
SELECT LastName, SalesYTD
FROM Sales.vSalesPerson
ORDER BY LastName
:Out C:\Data\SqlCmdOutput.txt



Editing SQLCMD Scripts with Query Editor : http://msdn.microsoft.com/en-us/library/ms174187.aspx


'SQL Server 2005' 카테고리의 다른 글

SQL의 SHFT 비트 연산  (0) 2009.01.13
SQL Server, SANs and Virtualisation  (0) 2009.01.09
DB의 Collation  (0) 2009.01.07
인덱스 사용중인 상태 체크  (0) 2009.01.07
사용하지 않은 인덱스 찾기  (0) 2009.01.07

DB의 Collation


아.. 매일 헷깔린다 ㅜ.ㅜ
아.. 나이들었나? 졸립기두 하구 ㅜ.....ㅜ



SortRules

사전 정렬을 지정했을 때 정렬 규칙이 적용되는 알파벳 또는 언어를 나타내는 문자열입니다. 예를 들면 Latin1_General 또는 Polish 등이 있습니다.

Pref

대문자 우선을 지정합니다.

Codepage

데이터 정렬에 사용되는 코드 페이지를 표시하는 1 - 4자리 숫자를 지정합니다. CP1은 코드 페이지 1252를 지정하며 다른 모든 코드 페이지에 대해서는 완전한 코드 페이지 번호를 지정합니다. 예를 들어 CP1251은 코드 페이지 1251을 지정하며 CP850은 코드 페이지 850을 지정합니다.

CaseSensitivity

CI는 대/소문자 구분 안 함을, CS는 대/소문자 구분을 지정합니다.

AccentSensitivity

AI는 악센트 구분 안 함을, AS는 악센트 구분을 지정합니다.

BIN

이진 정렬 순서를 사용하도록 지정합니다.

~
 

 

'SQL Server 2005' 카테고리의 다른 글

SQL Server, SANs and Virtualisation  (0) 2009.01.09
The sqlcmd utility in SQL Server  (0) 2009.01.08
인덱스 사용중인 상태 체크  (0) 2009.01.07
사용하지 않은 인덱스 찾기  (0) 2009.01.07
데이타베이스 샘플 사이트  (0) 2008.12.16

SQL2005의 DMV의 기능이 강화되었다고 하는데,, 이것까지 가능한지 몰랐다. 와우.ㅋㅋ


SELECT o.name Object_Name,
       SCHEMA_NAME(o.schema_id) Schema_name,
       i.name Index_name,
       i.Type_Desc,
       s.user_seeks,
       s.user_scans,
       s.user_lookups,
       s.user_updates 
FROM sys.objects AS o
 JOIN sys.indexes AS i
ON o.object_id = i.object_id
 JOIN
sys.dm_db_index_usage_stats AS s   
ON i.object_id = s.object_id  
AND i.index_id = s.index_id
WHERE  o.type = 'u'
-- Clustered and Non-Clustered indexes
AND i.type IN (1, 2)
-- Indexes that have been updated by not used
AND(s.user_seeks > 0 or s.user_scans > 0 or s.user_lookups > 0 );

SELECT o.name Object_Name,
       i.name Index_name,
       i.Type_Desc
 FROM sys.objects AS o
     JOIN sys.indexes AS i
 ON o.object_id = i.object_id
  LEFT OUTER JOIN
  sys.dm_db_index_usage_stats AS s   
 ON i.object_id = s.object_id  
  AND i.index_id = s.index_id
 WHERE  o.type = 'u'
 -- Clustered and Non-Clustered indexes
  AND i.type IN (1, 2)
  -- Indexes without stats
  AND (s.index_id IS NULL) OR
  -- Indexes that have been updated by not used
      (s.user_seeks = 0 AND s.user_scans = 0 AND s.user_lookups = 0 );