Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)

SqlCommand를 이용해 Microsoft SQL 서버의 쿼리 실행 계획을 구하는 방법

보통, SSMS 도구를 이용해 쿼리 실행 계획을 보게 되는데요. 직접 쿼리해서 구해오는 것도 가능합니다.

How do I obtain a Query Execution Plan?
; http://stackoverflow.com/questions/7359702/how-do-i-obtain-a-query-execution-plan

위의 글에 설명된 것처럼, 다음의 5가지 중에 하나를 실행해 주면 이후의 쿼리에 대해 실행 계획을 별도의 resultset으로 반환받게 됩니다.

  • SET SHOWPLAN_TEXT ON
  • SET SHOWPLAN_ALL ON
  • SET SHOWPLAN_XML ON
  • SET STATISTICS PROFILE ON
  • SET STATISTICS XML ON

동작 유무를 확인하기 위해 곧바로 SSMS의 쿼리 창에서 직접 테스트를 해볼 수도 있겠지요. ^^

getting an execution plan in C#
; http://dbaspot.com/sqlserver-programming/467308-getting-execution-plan-c.html

제 테스트 DB에서는 다음과 같은 쿼리를 수행해 봤고,

USE UnitTestDB2
GO

SET SHOWPLAN_TEXT ON
go

select * from mytable
go

SET SHOWPLAN_TEXT OFF
GO

예상했던대로 SSMS에서는 2개의 resultset으로 결과를 반환하는데, 하나는 쿼리 수행 문이고 또 다른 하나는 쿼리 실행 계획입니다.

query_plan_in_cs_1.png




그런데, C#에서 ADO.NET을 이용해 쿼리를 수행하는 경우 이를 하나의 Command에 넣으면 오류가 발생합니다.

command.CommandText = "SET SHOWPLAN_TEXT ON; select * from mytable; SET SHOWPLAN_TEXT OFF";
reader = command.ExecuteReader();

Unhandled Exception: System.Data.SqlClient.SqlException: The SET SHOWPLAN statements must be the only statements in the batch.
   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
   ...[생략]...
   at ConsoleApplication1.Program.Main(String[] args) in d:\...\ConsoleApplication1\Program.cs:line 28

즉, 한 줄에 넣으면 안 되고 하나의 Connection에 연이어서 쿼리를 수행해야 합니다.

command.CommandText = "SET SHOWPLAN_TEXT ON";
command.ExecuteNonQuery();

command.CommandText = "select * from mytable";
reader = command.ExecuteReader();

if (reader != null)
{
    using (reader)
    {
        do
        {
            while (reader.Read())
            {
                Console.WriteLine(reader[0]);
            }

        } while (reader.NextResult());
    }
}

command.CommandText = "SET SHOWPLAN_TEXT OFF";
command.ExecuteNonQuery();

그런데, 재미있는 특징이 하나 있습니다. 일반적으로 ADO.NET 쿼리 실행 시에 Parameterized Query 방식을 쓰게 되는데요.

command.CommandText = "SET SHOWPLAN_TEXT ON; ";
command.ExecuteNonQuery();

SqlParameter param = new SqlParameter("@id", System.Data.SqlDbType.Int);
param.Value = 0;
command.Parameters.Add(param);
command.CommandText = "select * from mytable WHERE id <> @id";
reader = command.ExecuteReader();

일단 이렇게 Command.Parameters 컬렉션에 인자가 들어가면 해당 쿼리 수행은 실행 계획의 영향을 받지도 않을 뿐더러 그렇다고 쿼리가 수행되지도 않습니다. 그냥 결과 자체를 반환하지 않습니다.

그럼 어떻게 하냐고요? ^^ 할 수 없습니다. 그냥 ad-hoc 쿼리 식으로 입력해 줘야 합니다.

command.CommandText = "SET SHOWPLAN_TEXT ON; ";
command.ExecuteNonQuery();

command.CommandText = "select * from mytable WHERE id <> 0";
reader = command.ExecuteReader();

성공하면 첫 번째 resultset에서 쿼리를 얻고,

select * from mytable WHERE id <> 0 

다음 resultset에서 실행 계획을 얻습니다.

  |--Clustered Index Seek(OBJECT:([UnitTestDB2].[dbo].[mytable].[PK_mytable]), S
EEK:([UnitTestDB2].[dbo].[mytable].[id] < (0) OR [UnitTestDB2].[dbo].[mytable].[
id] > (0)) ORDERED FORWARD)

(첨부된 파일은 위의 소스 코드를 반영한 프로젝트입니다.)




참고로 자바의 경우 "Microsoft SQL Server JDBC Driver"를 이용해서,

자바에서 "Microsoft SQL Server JDBC Driver" 사용하는 방법
; https://www.sysnet.pe.kr/2/0/1116

다음과 같은 소스코드로 가져올 수 있습니다.

import java.sql.*;

public class DBTest {

    public static void main(String[] args) 
    {
        String connectionString = "jdbc:sqlserver://...[서버주소]...:1433;databaseName=...[DB명]...;user=...[계정]...;password=...[암호]...";
            
        Connection con = null;
        Statement stmt = null;
        ResultSet rs = null;
              
        try {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            con = DriverManager.getConnection(connectionString);

            String plan = "SET SHOWPLAN_TEXT ON";
            stmt = con.createStatement();
            stmt.execute(plan);

            String SQL = "SELECT * FROM Account";
            stmt = con.createStatement();
            rs = stmt.executeQuery(SQL);
                
            while (rs.next()) {
                System.out.println(rs.getString(1));
            }
                
            stmt.getMoreResults();
            rs = stmt.getResultSet();
                
            while (rs.next()) {
                System.out.println(rs.getString(1));
            }
                
            plan = "SET SHOWPLAN_TEXT OFF";
            stmt = con.createStatement();
            stmt.execute(plan);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            if (rs != null) try { rs.close(); } catch(Exception e) {}
            if (stmt != null) try { stmt.close(); } catch(Exception e) {}
            if (con != null) try { con.close(); } catch(Exception e) {}
        }
    }
}





[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 10/17/2021]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 31  32  33  34  35  [36]  37  38  39  40  41  42  43  44  45  ...
NoWriterDateCnt.TitleFile(s)
12756정성태8/6/20218525.NET Framework: 1084. C# - .NET Core Web API 단위 테스트 방법 [1]파일 다운로드1
12755정성태8/5/20217774개발 환경 구성: 593. MSTest - 단위 테스트에 static/instance 유형의 private 멤버 접근 방법파일 다운로드1
12754정성태8/5/20218590오류 유형: 750. manage.py - Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
12753정성태8/5/20218907오류 유형: 749. PyCharm - Error: Django is not importable in this environment
12752정성태8/4/20216943개발 환경 구성: 592. JetBrains의 IDE(예를 들어, PyCharm)에서 Visual Studio 키보드 매핑 적용
12751정성태8/4/202110080개발 환경 구성: 591. Windows 10 WSL2 환경에서 docker-compose 빌드하는 방법
12750정성태8/3/20216836디버깅 기술: 181. windbg - 콜 스택의 "Call Site" 오프셋 값이 가리키는 위치
12749정성태8/2/20216239개발 환경 구성: 590. Visual Studio 2017부터 단위 테스트에 DataRow 특성 지원
12748정성태8/2/20216874개발 환경 구성: 589. Azure Active Directory - tenant의 관리자(admin) 계정 로그인 방법
12747정성태8/1/20217413오류 유형: 748. 오류 기록 - MICROSOFT GRAPH – HOW TO IMPLEMENT IAUTHENTICATIONPROVIDER파일 다운로드1
12746정성태7/31/20219528개발 환경 구성: 588. 네트워크 장비 환경을 시뮬레이션하는 Packet Tracer 프로그램 소개
12745정성태7/31/20217314개발 환경 구성: 587. Azure Active Directory - tenant의 관리자 계정 로그인 방법
12744정성태7/30/20217963개발 환경 구성: 586. Azure Active Directory에 연결된 App 목록을 확인하는 방법?
12743정성태7/30/20218657.NET Framework: 1083. Azure Active Directory - 외부 Token Cache 저장소를 사용하는 방법파일 다운로드1
12742정성태7/30/20217822개발 환경 구성: 585. Azure AD 인증을 위한 사용자 인증 유형
12741정성태7/29/20219054.NET Framework: 1082. Azure Active Directory - Microsoft Graph API 호출 방법파일 다운로드1
12740정성태7/29/20217701오류 유형: 747. SharePoint - InvalidOperationException 0x80131509
12739정성태7/28/20217635오류 유형: 746. Azure Active Directory - IDW10106: The 'ClientId' option must be provided.
12738정성태7/28/20218319오류 유형: 745. Azure Active Directory - Client credential flows must have a scope value with /.default suffixed to the resource identifier (application ID URI).
12737정성태7/28/20217205오류 유형: 744. Azure Active Directory - The resource principal named api://...[client_id]... was not found in the tenant
12736정성태7/28/20217787오류 유형: 743. Active Azure Directory에서 "API permissions"의 권한 설정이 "Not granted for ..."로 나오는 문제
12735정성태7/27/20218373.NET Framework: 1081. C# - Azure AD 인증을 지원하는 데스크톱 애플리케이션 예제(Windows Forms) [2]파일 다운로드1
12734정성태7/26/202124458스크립트: 20. 특정 단어로 시작하거나/끝나는 문자열을 포함/제외하는 정규 표현식 - Look-around
12733정성태7/23/202111579.NET Framework: 1081. Self-Contained/SingleFile 유형의 .NET Core/5+ 실행 파일을 임베딩한다면? [1]파일 다운로드2
12732정성태7/23/20216803오류 유형: 742. SharePoint - The super user account utilized by the cache is not configured.
12731정성태7/23/20218339개발 환경 구성: 584. Add Internal URLs 화면에서 "Save" 버튼이 비활성화 된 경우
... 31  32  33  34  35  [36]  37  38  39  40  41  42  43  44  45  ...