[SQL] SQL Server - Trace Stop & Close & Remove

SQL Server에서 Trace를 멈추거나 제거할 때 사용하는 SQL
(서비스 중간에 긴급하게 잠시동안 Profiler를 실행한 후 종료가 되지 않을 때 유용)
-------------------------------------------------------------------
--서버에 존재하고 있는 trace 정보를 반환한다.
-- traceid : Trace id
-- property : Trace property
-- 1= 추적 옵션
-- 2 = 파일 이름
-- 3 = 최대 크기
-- 4 = 중지 시간
-- 5 = 현재 추적 상태. 0 = 중지됨. 1 = 실행 중.
-- value : Property value.
-------------------------------------------------------------------
DECLARE @v_traceid INT
SELECT @v_traceid  = null --NULL=ALL
SELECT *
FROM ::fn_trace_getinfo(@v_traceid)
--------------------------------------------------------------------
--------------------------------------------------
-- Define constant.
DECLARE @STOP INT
DECLARE @START INT
DECLARE @CLOSE_REMOVE INT
SELECT @STOP = 0
SELECT @START = 1
SELECT @CLOSE_REMOVE = 2
--------------------------------------------------
DECLARE @v_traceid INT
SELECT @v_traceid = 2
--지정한 trace id를 상태를 변경한다.
--아래는 trace id 2를 서버에서 닫고 제거한다.
exec sp_trace_setstatus @traceid=@v_traceid  , @status=@CLOSE_REMOVE
-- trace id 2  닫고 제거되었기 때문에 반환하는 정보가 없다.
SELECT *
FROM ::fn_trace_getinfo(@v_traceid)
---------------------------------------------------
출처 : 직접 작성.
이올린에 북마크하기(0) 이올린에 추천하기(0)

Posted by 좐군

2011/10/11 14:46 2011/10/11 14:46
,
Response
No Trackback , No Comment
RSS :
http://John.tobe30.com/tc/rss/response/336

Trackback URL : http://John.tobe30.com/tc/trackback/336

Leave a comment
[로그인][오픈아이디란?]

This step-by-step article describes how to install a certificate on a computer that is running Microsoft SQL Server 2000 or Microsoft SQL Server 2005 by using Microsoft Management Console (MMC) and describes how to enable SSL Encryption at the server, or for specific clients.

Note You cannot use this method to put a certificate on a SQL Server clustered server.

If your company has implemented an Enterprise Certificate Authority, you can request certificates for a SQL Server stand-alone server, and then use the certificate for Secure Sockets Layer (SSL) encryption.

You can enable the
Force Protocol Encryption option on the server, or on the client.

Note Do not enable the Force Protocol Encryption option on both the client and the server. To enable Force Protocol Encryption on the server, use the Server Network Utility. To enable Force Protocol Encryption on the client, use the Client Network Utility.

Important If you enable SSL encryption by using the Client Network Utility, then all connections from that client will request SSL encryption to any SQL Server to which that client connects.

Warning If you enable Force Protocol Encryption on the client computer, you cannot connect to previous versions of SQL Server from that specific client. Previous versions of SQL Server do not recognize SSL encryption.

If you enable
Force Protocol Encryption on the server, you must install a certificate on the server.

If you want to enable
Force Protocol Encryption on the client, you must have a certificate on the server and the client must have the Trusted Root Authority updated to trust the server certificate.

Note If you are using SQL Server 2005 to enable encrypted connections for an instance of SQL Server 2005, you can set the value of the ForceEncryption option to Yes. For more information, see the "How to: Enable Encryption Connections to the Database Engine (SQL Server Configuration Manager)" topic in SQL Server 2005.

[Install a certificate on a server with Microsoft Management Console (MMC)]

To use SSL encryption, you must install a certificate on the server. Follow these steps to install the certificate by using the Microsoft Management Console (MMC) snap-in.

How to Configure the MMC Snap-in
  1. To open the Certificates snap-in, follow these steps:
    1. To open the MMC console, click Start, and then click Run. In the Run dialog box type:

      MMC
    2. On the Console menu, click Add/Remove Snap-in....
    3. Click Add, and then click Certificates. Click Add again.
    4. You are prompted to open the snap-in for the current user account, the service account, or for the computer account. Select the Computer Account.
    5. Select Local computer, and then click Finish.
    6. Click Close in the Add Standalone Snap-in dialog box.
    7. Click OK in the Add/Remove Snap-in dialog box. Your installed certificates are located in the Certificates folder in the Personal container.
  2. Use the MMC snap-in to install the certificate on the server:
    1. Click to select the Personal folder in the left-hand pane.
    2. Right-click in the right-hand pane, point to All Tasks, and then click Request New Certificate....
    3. The Certificate Request Wizard dialog box opens. Click Next. Select Certificate type is "computer".
    4. In the Friendly Name text box you can type a friendly name for the certificate or leave the text box blank, and then complete the wizard. After the wizard finishes, you will see the certificate in the folder with the fully qualified computer domain name.

    5. If you want to enable encryption for a specific client or clients, skip this step and proceed to the Enable encryption for a specific client section of this article.

      If you want to enable encryption at the server, open the Server Network Utility on the server where the certificate is installed, and then click to select the
      Force protocol encryption check box. Restart the MSSQLServer (SQL Server) service for the encryption to take effect. Your server is now ready to use SSL encryption.

[Enable encryption for a specific client]

For the client to request the SSL encryption, the client computer must trust the server certificate and the certificate must already exist on the server. You have to use the MMC snap-in to export the Trusted Root Certification Authority used by the server certificate:
  1. To export the server certificate's Trusted Root Certificate Authority (CA), follow these steps:
    1. Open MMC, and then locate your certificate in the Personal folder.
    2. Right-click the certificate name, and then click Open.
    3. Review the Certification Path tab. Note the top most item.
    4. Navigate to the Trusted Root Certification Authorities folder, and then locate the Certificate Authority noted in step c..
    5. Right-click CA, point to All Tasks, and then click Export.
    6. Select all the defaults, and then save the exported file to your disk where the client computer can access the file.
  2. Follow these steps to import the certificate on the client computer:
    1. Navigate to the client computer by using the MMC snap-in, and then browse to the Trusted Root Certification Authorities folder.
    2. Right-click the Trusted Root Certification Authorities folder, point to All Tasks, and then click Import.
    3. Browse, and then select the certificate (.cer file) that you generated in step 1. Select the defaults to complete the remaining part of the wizard.
    4. Use the SQL Server Client Network Utility.
    5. Click to select the Force Protocol encryption option. Your client is now ready to use SSL encryption.

[How to test your client connection]

To test your client connection you can either:
  • Use the Query Analyzer Tool.

    -or-

  • Use any ODBC application where you can change the connection string.
Query Analyzer Tool

To use the Query Analyzer Tool, follow these steps:
  1. Use the SQL Server Client Network Utility.
  2. Click to select the Force protocol encryption option.
  3. Connect to the server that is running SQL Server 2000 by using Query Analyzer.
  4. Monitor the communication by using Microsoft Network Monitor or a Network Sniffer.
ODBC or OLEDB Application Sample Connection Strings

If you use ODBC or OLEDB connection strings, follow these steps:
  1. Modify the ODBC or OLEDB connection string. For example:

    ODBC
    Driver=SQLServer;Server=ServerNameHere;UID=UserIdHere;PWD=PasswordHere;Network=DBNETLIB.DLL;Encrypt=YES
    OLEDB
    Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=dbNameHere;Data Source=ServerNameHere;Use Encryption for Data=True
  2. Connect to the server that is running SQL Server 2000, and then monitor the communication by using Microsoft Network Monitor or a Network Sniffer.

[Troubleshooting]

After you successfully install the certificate, the certificate does not appear in the Certificate list on the Certificate tab.

Note The Certificate tab is in the Protocols for <InstanceName> Properties dialog box that is opened from SQL Server Configuration Manager.

This issue occurs because you may have installed an invalid certificate. If the certificate is invalid, it will not be listed on the
Certificate tab. To determine whether the certificate that you installed is valid, follow these steps:
  1. Open the Certificates snap-in. To do this, see step 1 in the "How to Configure the MMC Snap-in" section.
  2. In the Certificates snap-in, expand Personal, and then expand Certificates.
  3. In the right pane, locate the certificate that you installed.
  4. Determine whether the certificate meets the following requirements:
    • In the right pane, the value in the Intended Purpose column for this certificate must be Server Authentication.
    • In the right pane, the value in the Issued To column must be the server name.
  5. Double-click the certificate, and then determine whether the certificate meets the following requirements:
    • On the General tab, you receive the following message:
      You have a private key that corresponds to this certificate.
    • On the Details tab, the value for the Subject field must be server name.
    • The value for the Enhanced Key Usage field must be Server Authentication (<number>).
    • On the Certification Path tab, the server name must appear under Certification path.
If any one of these requirements is not met, the certificate is invalid.
이올린에 북마크하기(0) 이올린에 추천하기(0)

Posted by 좐군

2009/11/28 23:50 2009/11/28 23:50
,
Response
No Trackback , No Comment
RSS :
http://John.tobe30.com/tc/rss/response/241

Trackback URL : http://John.tobe30.com/tc/trackback/241

Leave a comment
[로그인][오픈아이디란?]

[펌]SQL Server 2005 connectivity error messages

One of the more visible changes we made in connectivity space for SQL Server 2005 was enhancing error messages reported to the user in case of connection failures.  I have seen several cases over the last several months, and in this post I would like to list some of them with the root cause that caused them.  The cause may not be the only one triggering a particular error message, and there may be other error messages of interest. 

This is a semi-random selection from real cases I investigated.  Likely I will post another batch some time in the future, and I would be happy to see replies with additional errors, particularly if the root cause is unclear. 

The examples are from various client stacks – ODBC or OLEDB from SQL Native Client or from managed SqlClient. 

The exact formatting of the messages will depend on the application you use.  Most of the examples below used OSQL, SQLCMD, or SQL Server Management Studio. 

  • Connecting to a server by the server’s name from SqlClient, the server name is aliased to TCP, the server is up and running but it does not listen on TCP (or is not running at all):

An error has occurred while establishing a connection to the server.  When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections. (provider: TCP Provider, error: 0 - No connection could be made because the target machine actively refused it.) (Microsoft SQL Server, Error: 10061)

  • Local connection from SqlClient; server is not running:

(a) default instance:

An error has occurred while establishing a connection to the server.  When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server) (Microsoft SQL Server, Error: 2)

(b) named instance:

An error has occurred while establishing a connection to the server.  When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections. (provider: Shared Memory Provider, error: 40 - Could not open a connection to SQL Server) (Microsoft SQL Server, Error: 2)

  • Remote connection from ODBC, Windows Firewall is turned on on the server machine but there is an exception for File and Printer Sharing:

 [SQL Native Client]Unable to complete login process due to delay in opening server connection

  • A successful TCP connection from SqlClient to the server was broken due to a TCP keep-alive heartbeat failure (typically indicating problems with the underlying network infrastructure):

A transport-level error has occurred when receiving results from the server. (provider: TCP Provider, error: 0 - The specified network name is no longer available.)

Possibly:

A transport-level error has occurred when sending the request to the server. (provider: TCP Provider, error: 0 - An existing connection was forcibly closed by the remote host.)

  • OBDC connection attempt when server is not ready to process a new local connection, possibly due to overload: 

[SQL Native Client]Shared Memory Provider: Timeout error [258].
[SQL Native Client]Login timeout expired
[SQL Native Client]Unable to complete login process due to delay in prelogin response

[SQL Native Client]Shared Memory Provider: Could not open a connection to SQL Server [121].
[SQL Native Client]Login timeout expired
[SQL Native Client]An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections.

  • There is a space after server name in the connection string:

osql -E -S "<serverName> ,1433"
Login failed for user ''. The user is not associated with a trusted SQL Server connection.

The server ERRORLOG/EventLog shows something similar to:

2005-08-11 12:46:04.29 Logon       Error: 17806, Severity: 20, State: 2.
2005-08-11 12:46:04.29 Logon       SSPI handshake failed with error code 0x8009030c while establishing a connection with integrated security; the connection has been closed. [CLIENT: <IP address>]
2005-08-11 12:46:04.29 Logon       Error: 18452, Severity: 14, State: 1.
2005-08-11 12:46:04.29 Logon       Login failed for user ''. The user is not associated with a trusted SQL Server connection. [CLIENT: <IP address>]

  • Remote OLEDB connection using TCP to a server that is blocked by Firewall

HResult 0x274C, Level 16, State 1
TCP Provider: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.

Error: Microsoft SQL Native Client : An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections..
Error: Microsoft SQL Native Client : Login timeout expired.

  • Remote OLEDB connection using TCP to a server that is either not running or does not have TCP/IP protocol enabled for incoming connections (but is not blocked by the Firewall on the server machine):

HResult 0x274D, Level 16, State 1
TCP Provider: No connection could be made because the target machine actively refused it.

Error: Microsoft SQL Native Client : An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections..
Error: Microsoft SQL Native Client : Login timeout expired.

출처 : http://blogs.msdn.com/sql_protocols/archive/2005/09/28/474698.aspx


이올린에 북마크하기(0) 이올린에 추천하기(0)

Posted by 좐군

2009/11/28 23:19 2009/11/28 23:19
,
Response
No Trackback , No Comment
RSS :
http://John.tobe30.com/tc/rss/response/240

Trackback URL : http://John.tobe30.com/tc/trackback/240

Leave a comment
[로그인][오픈아이디란?]

SSMS 에 Add-in인 SSMS Tool Pack을 소개하려 한다.  SSMS2005 버전과 SSMS2008 버전이 별도로 존재하므로 알맞은 버전을 설치해야 한다.
다운로드 : http://www.ssmstoolspack.com/Download.aspx
SSMS Tool Pack 은 다음과 기능을 제공한다.
( 필자의 경우 테이블에 데이터를 INSERT-SQL로 생성해주는 기능을 아주 유용하게 사용하고 있다.)


Features
Source : http://www.ssmstoolspack.com/Features.aspx
With windows connection color indicator you always know to which server you're connected to. The color strip can be docked to any side of the window and it's color can be easily changed from either it's context menu or from server coloring options.
Coloring for each server can be added, removed or just disabled.
Window Connection Coloring Thumbnail



Query Execution History (Soft Source Control) and Current Window History
Every SQL statement that you run is logged in a file on your disk or in a table in a database you specify with a connection string. This way, if you're working on some script you can get the full history of every change you've made between check-out and check-in of your file.
SQL Statements are saved in a list that is written to a file and/or a database with a timer which you can set to a desired interval.

Older query history logs can be auto deleted. Time after the logs are deleted is user settable.
Query Execution History Thumbnail
Current window history is a dockable window that show queries executed in a currently active window. There is also a search box at the top that filters results as you type. Current History Window Thumbnail




Search Table or Database Data
Simple search for a search term through all non-binary columns in a single table or in every table of a database. You can search in four ways: Contains, Starts with, Ends with and Equals.
Search Table or Database Thumbnail


Uppercase/Lowercase keywords and proper case Database Object Names
Set all keywords to uppercase or lowercase letters. Custom keywords can be added.
Format all database objects to their proper case sensitive name.
Format text Thumbnail


Run one script on multiple databases
Run selected or full window text on selected databases on the currently connected server. A new window is opened that contains one script for all databases. Run one script on multiple databases Thumbnail


Copy execution plan bitmaps to clipboard
Copy selected or all execution plans to a bitmap that is saved on the clipboard. Large execution plans that don't fit in the window are also copied in full.
Width of a picture containing all execution plans is equal to the width of the widest execution plan.
Copy execution plan bitmaps to clipboard Thumbnail


Search Results in Grid Mode and Execution Plans
Find all occurrences of your search string in the execution plans or in the results in datagrid mode.
Search results and execution plans Thumbnail


Generate Insert statements for a single table, the whole database or current resultsets in grids
Insert statements for the whole database are generated by the order of PK-FK relationships. Top tables with no FK's are scripted first. Binary data is by default fully scripted. If you wish you can also set the scripting data limit between 0 and 10 Mb. Larger values then the limit are then scripted as NULL.

Insert statements for the data in result grids are scripted into a new temporary table for each grid. For example from 5 result grids insert statements for 5 temporary tables get created.
Generate insert statements Thumbnail


Text document Regions and Debug sections
Regions behave in the same way as in Visual Studio. You can collapse them and expand them. Debug sections are sections that get commented or deleted when you change your script to Release configuration. A debug section is also a collapsable region. If you deploy a script in debug mode with added debug sections it will fail when run from SSMS without SSMS Tools Pack installed. You can of course comment those sections yourself by simply searching for start and end text of the debug sections. Regions and Debug section Thumbnail


Running custom scripts from Object explorer's Context menu
You can specify a custom script text, its name and node on Object Explorer on which you want to run it from. Node name, current database, current connection string and current server can also be specified in the custom script with keywords that are replaced with their respective values at script runtime. Run custom script Thumbnail


CRUD (Create, Read, Update, Delete) stored procedure generation
CRUD stored procedure generation for tables based on fully customizable templates that you can change to suit your needs. CRUD Thumbnail


New query template
When opening a new query window you can specify a template that will be displayed. New query Template Thumbnail

이올린에 북마크하기(0) 이올린에 추천하기(0)

Posted by 좐군

2009/10/20 00:21 2009/10/20 00:21
, ,
Response
No Trackback , No Comment
RSS :
http://John.tobe30.com/tc/rss/response/222

Trackback URL : http://John.tobe30.com/tc/trackback/222

Leave a comment
[로그인][오픈아이디란?]
DECLARE @old_datefirst INT
SELECT @old_datefirst = @@DATEFIRST

DECLARE @v_dayname_monday INT
SELECT @v_dayname_monday = 1
SET DATEFIRST @v_dayname_monday

DECLARE @v_date DATETIME
SELECT @v_date = '2009-08-01'    ---특정 날짜 지정.

SELECT @v_date date
, DATEPART(year, @v_date) [Year]
, DATEPART(week, @v_date) [Week of Year]
, DATEPART(dayofyear, @v_date) [Day of Year]
, CASE
WHEN DATEPART(weekday, @v_date) > 1 THEN DATEADD(day, (DATEPART(weekday, @v_date)-1) * -1 , @v_date)
ELSE @v_date END [First-day of Week]
, CASE
WHEN DATEPART(weekday, @v_date) < 7 THEN DATEADD(day, 7-DATEPART(weekday, @v_date), @v_date)
ELSE @v_date END [Last-day of Week]

SET DATEFIRST @old_datefirst

/*
실행결과
date                 Year Week of Year Day of Year First-day of Week   Last-day of Week
2009-08-01 2009 31                         213                 2009-07-27            2009-08-02
*/
이올린에 북마크하기(0) 이올린에 추천하기(0)

Posted by 좐군

2009/08/20 22:00 2009/08/20 22:00
, ,
Response
No Trackback , No Comment
RSS :
http://John.tobe30.com/tc/rss/response/189

Trackback URL : http://John.tobe30.com/tc/trackback/189

Leave a comment
[로그인][오픈아이디란?]

[SQL Server]sp_reset_connection이 무엇을 하는가?

What does sp_reset_connection do?

Data access API's layers like ODBC, OLE-DB and SqlClient call the (internal) stored procedure sp_reset_connection when re-using a connection from a connection pool. It does this to reset the state of the connection before it gets re-used, however nowhere is documented what things get reset. This article tries to document the parts of the connection that get reset.

sp_reset_connection resets the following aspects of a connection:

  • It resets all error states and numbers (like @@error)
  • It stops all EC's (execution contexts) that are child threads of a parent EC executing a parallel query
  • It will wait for any outstanding I/O operations that is outstanding
  • It will free any held buffers on the server by the connection
  • It will unlock any buffer resources that are used by the connection
  • It will release all memory allocated owned by the connection
  • It will clear any work or temporary tables that are created by the connection
  • It will kill all global cursors owned by the connection
  • It will close any open SQL-XML handles that are open
  • It will delete any open SQL-XML related work tables
  • It will close all system tables
  • It will close all user tables
  • It will drop all temporary objects
  • It will abort open transactions
  • It will defect from a distributed transaction when enlisted
  • It will decrement the reference count for users in current database; which release shared database lock
  • It will free acquired locks
  • It will releases any handles that may have been acquired
  • It will reset all SET options to the default values
  • It will reset the @@rowcount value
  • It will reset the @@identity value
  • It will reset any session level trace options using dbcc traceon()

sp_reset_connection will NOT reset:
  • Security context, which is why connection pooling matches connections based on the exact connection string.
  • If you entered an application role using sp_setapprole, since application roles can not be reverted.

To learn more about connection pooling see Pooling in the Microsoft Data Access Components.


            
이올린에 북마크하기(0) 이올린에 추천하기(0)

Posted by 좐군

2009/05/12 12:59 2009/05/12 12:59
, , ,
Response
No Trackback , No Comment
RSS :
http://John.tobe30.com/tc/rss/response/139

Trackback URL : http://John.tobe30.com/tc/trackback/139

Leave a comment
[로그인][오픈아이디란?]

[펌]SQL Server Storage Top 10 Best Practices

Storage Top 10 Best Practices

원문 : http://www.microsoft.com/technet/prodtechnol/sql/bestpractice/storage-top-10.mspx

Proper configuration of IO subsystems is critical to the optimal performance and operation of SQL Server systems. Below are some of the most common best practices that the SQL Server team recommends with respect to storage configuration for SQL Server.

1

Understand the IO characteristics of SQL Server and the specific IO requirements / characteristics of your application.

In order to be successful in designing and deploying storage for your SQL Server application, you need to have an understanding of your application’s IO characteristics and a basic understanding of SQL Server IO patterns. Performance monitor is the best place to capture this information for an existing application. Some of the questions you should ask yourself here are:

What is the read vs. write ratio of the application?

What are the typical IO rates (IO per second, MB/s & size of the IOs)? Monitor the perfmon counters:

1.

Average read bytes/sec, average write bytes/sec

2.

Reads/sec, writes/sec

3.

Disk read bytes/sec, disk write bytes/sec

4.

Average disk sec/read, average disk sec/write

5.

Average disk queue length

How much IO is sequential in nature, and how much IO is random in nature? Is this primarily an OLTP application or a Relational Data Warehouse application?

To understand the core characteristics of SQL Server IO, refer to SQL Server 2000 I/O Basics.

2

More / faster spindles are better for performance

Ensure that you have an adequate number of spindles to support your IO requirements with an acceptable latency.

Use filegroups for administration requirements such as backup / restore, partial database availability, etc.

Use data files to “stripe” the database across your specific IO configuration (physical disks, LUNs, etc.).

3

Try not to “over” optimize the design of the storage; simpler designs generally offer good performance and more flexibility.

Unless you understand the application very well avoid trying to over optimize the IO by selectively placing objects on separate spindles.

Make sure to give thought to the growth strategy up front. As your data size grows, how will you manage growth of data files / LUNs / RAID groups? It is much better to design for this up front than to rebalance data files or LUN(s) later in a production deployment.

4

Validate configurations prior to deployment

Do basic throughput testing of the IO subsystem prior to deploying SQL Server. Make sure these tests are able to achieve your IO requirements with an acceptable latency. SQLIO is one such tool which can be used for this. A document is included with the tool with basics of testing an IO subsystem. Download the SQLIO Disk Subsystem Benchmark Tool.

Understand that the of purpose running the SQLIO tests is not to simulate SQL Server’s exact IO characteristics but rather to test maximum throughput achievable by the IO subsystem for common SQL Server IO types.

IOMETER can be used as an alternative to SQLIO.

5

Always place log files on RAID 1+0 (or RAID 1) disks. This provides:

better protection from hardware failure, and

better write performance.

Note: In general RAID 1+0 will provide better throughput for write-intensive applications. The amount of performance gained will vary based on the HW vendor’s RAID implementations. Most common alternative to RAID 1+0 is RAID 5. Generally, RAID 1+0 provides better write performance than any other RAID level providing data protection, including RAID 5.

6

Isolate log from data at the physical disk level

When this is not possible (e.g., consolidated SQL environments) consider I/O characteristics and group similar I/O characteristics (i.e. all logs) on common spindles.

Combining heterogeneous workloads (workloads with very different IO and latency characteristics) can have negative effects on overall performance (e.g., placing Exchange and SQL data on the same physical spindles).

7

Consider configuration of TEMPDB database

Make sure to move TEMPDB to adequate storage and pre-size after installing SQL Server.

Performance may benefit if TEMPDB is placed on RAID 1+0 (dependent on TEMPDB usage).

For the TEMPDB database, create 1 data file per CPU, as described in #8 below.

8

Lining up the number of data files with CPU’s has scalability advantages for allocation intensive workloads.

It is recommended to have .25 to 1 data files (per filegroup) for each CPU on the host server.

This is especially true for TEMPDB where the recommendation is 1 data file per CPU.

Dual core counts as 2 CPUs; logical procs (hyperthreading) do not.

9

Don’t overlook some of SQL Server basics

Data files should be of equal size – SQL Server uses a proportional fill algorithm that favors allocations in files with more free space.

Pre-size data and log files.

Do not rely on AUTOGROW, instead manage the growth of these files manually. You may leave AUTOGROW ON for safety reasons, but you should proactively manage the growth of the data files.

10

Don’t overlook storage configuration bases

Use up-to-date HBA drivers recommended by the storage vendor

Utilize storage vendor specific drivers from the HBA manufactures website

Tune HBA driver settings as needed for your IO volumes. In general driver specific settings should come from the storage vendor. However we have found that Queue Depth defaults are usually not deep enough to support SQL Server IO volumes.

Ensure that the storage array firmware is up to the latest recommended level.

Use multipath software to achieve balancing across HBA’s and LUN’s and ensure this is functioning properly

Simplifies configuration & offers advantages for availability

Microsoft Multipath I/O (MPIO): Vendors build Device Specific Modules (DSM) on top of Driver Development Kit provided by Microsoft.

이올린에 북마크하기(0) 이올린에 추천하기(0)

Posted by 좐군

2009/01/09 02:10 2009/01/09 02:10
, , ,
Response
No Trackback , No Comment
RSS :
http://John.tobe30.com/tc/rss/response/56

Trackback URL : http://John.tobe30.com/tc/trackback/56

Leave a comment
[로그인][오픈아이디란?]

원문 : http://www.microsoft.com/technet/prodtechnol/sql/bestpractice/dw_perf_top10.mspx

Relational Data Warehouse or Reporting work loads are characterized by low volumes of very large transactions. These applications are often identified as having predominately read workloads (e.g. Decision Support, Analysis, and Reporting) with periodic feeds or batch loads. It is important to keep these characteristics in mind as we examine the significance of database design, resource utilization and system performance. The top performance bottlenecks or gotchas to avoid for Data Warehouse or Reporting applications are outlined below.

1

Database Design issue if….

Excessive sorting operations are performed. If you continually perform the same sorting operations over and over, you can avoid these with appropriate indexing.

Excessive RID lookups are performed on heap tables. RID lookups mean extra IOs are required to retrieve columns that are not in the index used. This can be avoided with covered nonclustered indexes.

Key lookups against the clustering keys look like joins however they are marked as “lookups” only in the XML showplan. These can be avoided with covered nonclustered indexes.

A potentially beneficial index is missing on join columns resulting in HASH joins. Indexes on join columns may avoid the hash.

2

CPU gotchas….

If signal waits > 25% of total waits, there is a CPU bottleneck. See sys.dm_os_wait_stats for Signal waits and Total waits. Signal waits measure the time spent in the runnable queue waiting for CPU. High signal waits indicate a CPU bottleneck.

Avoid inappropriate plan re-use. If the query is identical, then plan re-use is a good thing. However, query parameterization that allows plan re-use is only appropriate when the result set (and intermediate work tables) are of similar size to the original plan. If result set sizes vary significantly due to differing parameter values which are common in data warehouse scenarios, plan re-use can be detrimental. Bad plans can also lead to longer running queries and IO or memory pressure. Therefore, the cost of plan generation in such cases is preferable to plan re-use. Unlike OLTP, data warehouse queries are not always identical in terms of result sets or optimal query plans.

3

Memory bottleneck if….

Sudden big drop in page life expectancy. DW applications (e.g. big transactions) could experience big drops in page life expectancy. This is due to a cache flush from a big read. See Perfmon object SQL Server Buffer Manager.

Pending memory grants. See counter Memory Grants Pending, in the Perfmon object SQL Server Memory Manager. Large memory grants can be common in Data Warehouse applications. More memory may help, otherwise the user cannot execute until memory grant occurs.

Sudden drops or consistently low SQL Cache hit ratio. Drops or low cache hit may indicate memory pressure or missing indexes.

4

IO bottleneck if…

The best metric for write performance is disk seconds per read and disk seconds per write. When the IO system is NOT under significant load, there will be no disk queuing and thus disk seconds per read or write should be as good as it gets Normally it takes 4-8 milliseconds to complete a read when there is no IO pressure. Factors for IO throughput are the number of spindles, and drive throughput such as sequential and random IOs per second (according to the vendor). As the IO requests increase, you may notice disk queuing. The effects of queuing are reflected in high disk seconds per read or write. Periodic higher values for disk seconds/read may be acceptable for many applications. For high performance OLTP applications, sophisticated SAN subsystems provide greater IO scalability and resiliency in handling spikes of IO activity. Sustained high values for disk seconds/read (>15ms) does indicate a disk bottleneck.

High average disk seconds per write. See Perfmon Logical or Physical disk. Data Warehouse loads can be either logged with inserts, updates or deletes, or non-logged using bulk copy. Logged operations require transaction log writes. A transaction log write can be as fast as 1ms (or less) for high performance SAN environments. For many applications, a periodic spike in average disk seconds per write is acceptable considering the high cost of sophisticated SAN subsystems. However, sustained high values for average disk seconds/write is a reliable indicator of a disk bottleneck.

Big IOs such as table and range scans may be due to missing indexes.

5

Blocking bottleneck if….

Index contention. Look for high lock and latch waits in sys.dm_db_index_operational_stats. Compare with lock and latch requests.

High average row lock or latch waits. The average row lock or latch waits are computed by dividing lock and latch wait milliseconds (ms) by lock and latch waits. The average lock wait ms computed from sys.dm_db_index_operational_stats represents the average time for each block.

Block process report shows long blocks. See sp_configure “blocked process threshold” and Profiler “Blocked process Report” under the Errors and Warnings event.

High number of deadlocks. See Profiler “Graphical Deadlock” under Locks event to identify the statements involved in the deadlock.

6

Network bottleneck if….

High network latency coupled with an application that incurs many round trips to the database.

Network bandwidth is used up. See counters packets/sec and current bandwidth counters in the network interface object of Performance Monitor. For TCP/IP frames actual bandwidth is computed as packets/sec * 1500 * 8 /1000000 Mbps.

7

Wait statistics gotchas...

Since DataWarehouse and Reporting workloads are largely reads which are compatible with other reads, incompatible exclusive lock waits would ordinarily only come into play during batch loads or periodic feeds. If the top wait statistics are LCK_x. or PAGELATCH_EX, see “SQL Server 2005 Performance Tuning using Waits & Queues” for an explanation of sys.dm_os_wait_stats.

There is an IO bottleneck if top wait statistics in sys.dm_os_wait_stats are related to IO such as ASYNCH_IO_COMPLETION, IO_COMPLETION, LOGMGR, WRITELOG, or PAGEIOLATCH_x.

8

Indexing gotchas.

Large data warehouse can benefit from more indexes. Indexes can be used to cover queries and avoid sorting. For a data warehouse application, the cost of index overhead is only paid when data is loaded.

Check for missing indexes in sys.dm_db_missing_index_group_stats, sys.dm_db_missing_index_groups and sys.dm_db_missing_index_details

9

Watch out for fragmentation.

Excessive fragmentation is problematic for big IO operations. The Dynamic Management table valued function sys.dm_db_index_physical_stats returns the fragmentation percentage in the column avg_fragmentation_in_percent. Fragmentation should not exceed 25%. Reducing index fragmentation can benefit big range scans, common in data warehouse and Reporting scenarios

10

Consider Table Partitioning for fast loads

For the large tables common in Data Warehouses, table partitioning offers important performance and manageability advantages. For example, the fastest type of load is a non-logged bulk copy. The requirements for non-logged bulk copies are that indexes must be dropped. This is not feasible on a huge billion row table UNLESS you use table partitioning. This allows one to create a staging table identical to the large table (minus indexes). A fast non-logged bulk copy is used to load data. Thereafter, indexes are added to the staging table followed by constraints. Then, a meta-data only SWITCH IN operation switches pointer locations for the populated staging table and the empty target partition of the partitioned table resulting in an fully populated partition and empty staging table. Besides a fast bulk copy, the staging table allows us to eliminate blocking in the large partitioned table during the load. For more information refer to “Loading Bulk Data into Partitioned Tables”. In addition to fast loads, partitioned tables allow fast deletes (or archiving purposes or sliding window deletes) where large logged deletes are replaced with meta-data only partition SWITCH OUT operations that switches pointer locations for the full partition (to be ‘deleted’) and an empty monolithic table. The SWITCH OUT results in an empty partition and a fully populated monolithic staging table. Thereafter the monolithic table can either be dropped or added to a partitioned archive table using SWITCH IN. Partitions also provide manageability improvements when combined with specific filegroup placement, allowing for customized backup and restore strategies. 

이올린에 북마크하기(0) 이올린에 추천하기(0)

Posted by 좐군

2009/01/07 08:00 2009/01/07 08:00
, , ,
Response
No Trackback , No Comment
RSS :
http://John.tobe30.com/tc/rss/response/54

Trackback URL : http://John.tobe30.com/tc/trackback/54

Leave a comment
[로그인][오픈아이디란?]

[SQL]간단한 TREE 구조 구현

/*[테이블설계]*/

CREATE TABLE TreeMenu(
menu_cd int , --메뉴코드
menu_nm varchar(50) , --메뉴명
parent_cd int , --상위메뉴코드
CONSTRAINT PK_TreeMenu PRIMARY KEY (menu_cd)
)

/*[샘플데이터]*/
insert into TreeMenu VALUES(1, '시작'	   , 0)
insert into TreeMenu VALUES(2, '프로그램'	   , 1)
insert into TreeMenu VALUES(3, '설정' , 1) insert into TreeMenu VALUES(4, '보조프로그램', 2)
insert into TreeMenu VALUES(5, '제어판' , 3) insert into TreeMenu VALUES(6, '네트워크환경', 5)
insert into TreeMenu VALUES(7, '계산기' , 4) insert into TreeMenu VALUES(8, '그림판' , 4)
GO

/*[핵심함수 구현]*/
/***********************************************
트리구조에서 각 노드(행)의 절대위치를 Binary계산하는 함수
최대 64 Level 지원 ***********************************************/
go
CREATE FUNCTION FN_TreeOrderBy(
@root int, /*루트값*/
@menu_cd int /*현재값*/
) RETURNS varbinary(256)
BEGIN
DECLARE @parent_cd int ,
@level_bin varbinary(256)
IF @menu_cd = @root
BEGIN
RETURN 0
END
select @level_bin = CAST(@menu_cd AS varbinary(4)) --값 초기화
/*루프로 menu_cd위 절대위치 계산*/
WHILE 1 = 1
BEGIN
SELECT @parent_cd = parent_cd
FROM TreeMenu WITH(NOLOCK)
WHERE menu_cd = @menu_cd
IF (@root=@parent_cd or @parent_cd=0 or @parent_cd is null)
BEGIN
BREAK
END
SELECT @menu_cd = @parent_cd
SELECT @level_bin = CAST(@parent_cd AS varbinary(4)) + @level_bin
END
RETURN @level_bin
END
go

/*[함수사용하여 조회]*/
SELECT 	a.*	,
dbo.FN_TreeOrderBy(1, a.menu_cd) absolute_pos
FROM TreeMenu A WITH(NOLOCK)
ORDER BY absolute_pos --계산된 열로 정열
/*
속도를 더 빨리 하기 위한 방법으로는 삭제/수정/등록시
절대위치(absolute_pos)를 계산해서 저장하는 방법입니다. 저장된 절대위치에 클러스트인덱스 설정하면 검색속도가 더욱 빠릅니다
그래도
대용량 쿼리할 때 이용하기엔 쫌 부담이 되겠네요 -ㅅ-
*/
이올린에 북마크하기(0) 이올린에 추천하기(0)

Posted by 좐군

2008/12/19 23:15 2008/12/19 23:15
, , ,
Response
No Trackback , No Comment
RSS :
http://John.tobe30.com/tc/rss/response/39

Trackback URL : http://John.tobe30.com/tc/trackback/39

Leave a comment
[로그인][오픈아이디란?]
DECLARE    @cursor   CURSOR
,	@sql	NVARCHAR(1000)
,	@params	NVARCHAR(100)
DECLARE @id	INT
,	@name	NVARCHAR(200)

SELECT	@sql =N'SET @p_cur = CURSOR FORWARD_ONLY READ_ONLY FOR 
	SELECT top 10 id, name FROM dbo.sysobjects WITH(NOLOCK) WHERE id < 10;
	OPEN @p_cur'
SELECT	@params = N'@p_cur CURSOR OUTPUT'

EXEC sp_executesql
	@sql
,	@params
,	@p_cur	= @cursor	OUTPUT


FETCH NEXT FROM @cursor INTO @id, @name WHILE (@@FETCH_STATUS=0) BEGIN PRINT CAST(@id AS VARCHAR(10)) + ':' + @name FETCH NEXT FROM @cursor INTO @id, @name END CLOSE @cursor DEALLOCATE @cursor
이올린에 북마크하기(0) 이올린에 추천하기(0)

Posted by 좐군

2008/12/18 23:07 2008/12/18 23:07
, , ,
Response
No Trackback , No Comment
RSS :
http://John.tobe30.com/tc/rss/response/38

Trackback URL : http://John.tobe30.com/tc/trackback/38

Leave a comment
[로그인][오픈아이디란?]