programing

SQL Server Management Studio에서 쿼리 기록을 보는 방법

lastcode 2023. 4. 7. 21:26
반응형

SQL Server Management Studio에서 쿼리 기록을 보는 방법

쿼리 기록이 일부 로그 파일에 저장됩니까?만약 그렇다면, 그들의 위치를 찾는 방법을 가르쳐 주시겠습니까?만약 없다면, 어떻게 봐야 하는지 조언 좀 해주시겠어요?

[이 문제는 중복으로 종결될 가능성이 높기 때문에]

SQL Server가 재시작되지 않은 경우(계획이 제거되지 않은 경우 등), 계획 캐시에서 쿼리를 찾을 수 있습니다.

SELECT t.[text]
FROM sys.dm_exec_cached_plans AS p
CROSS APPLY sys.dm_exec_sql_text(p.plan_handle) AS t
WHERE t.[text] LIKE N'%something unique about your query%';

Management Studio가 충돌하여 파일을 손실한 경우 복구 파일을 다음 위치에서 찾을 수 있습니다.

C:\Users\<you>\Documents\SQL Server Management Studio\Backup Files\

그렇지 않으면 Ed Harper의 답변에 나와 있는 SSMS 도구 팩과 같은 쿼리 기록을 저장하기 위해 향후 다른 방법을 사용해야 합니다. 단, SQL Server 2012+에서는 무료로 제공되지 않습니다.또는 로그인 또는 호스트명으로 필터링된 경량 트레이스를 설정할 수도 있습니다(단, 이 경우 Profiler가 아닌 서버측 트레이스를 사용하십시오).


@코멘트처럼 @Nenad-Zivkovic, @Nenad-Zivkovic에 이 될 수 .sys.dm_exec_query_stats은 ★★★★★★★★★★★★★★★★★.last_execution_time:

SELECT t.[text], s.last_execution_time
FROM sys.dm_exec_cached_plans AS p
INNER JOIN sys.dm_exec_query_stats AS s
   ON p.plan_handle = s.plan_handle
CROSS APPLY sys.dm_exec_sql_text(p.plan_handle) AS t
WHERE t.[text] LIKE N'%something unique about your query%'
ORDER BY s.last_execution_time DESC;

늦었지만 좀 더 자세한 내용이 추가되어 도움이 될 것 같습니다.

기본적으로는 SSMS에서 실행된 쿼리를 볼 수 없습니다.하지만 몇 가지 선택지가 있습니다.

트랜잭션 로그 읽기– 독자적인 형식이기 때문에 쉽지 않습니다.단, (SELECT를 제외한) 이전에 실행된 쿼리를 표시할 필요가 있는 경우에는 이 방법밖에 없습니다.

ApexSQL Log 및 SQL Log Rescue와 같은 타사 도구를 사용할 수 있습니다(무료이지만 SQL 2000에만 해당).자세한 내용은 SQL Server 트랜잭션 로그 탐색기/분석기를 참조하십시오.

SQL Server 프로파일러– 감사를 시작하고 이전에 발생한 일에 관심이 없는 경우에 적합합니다.필터를 사용하여 필요한 트랜잭션만 선택해야 합니다.그렇지 않으면 엄청난 양의 데이터를 빠르게 얻을 수 있습니다.

SQL Server 추적 - 모든 또는 대부분의 명령을 캡처하여 나중에 구문 분석할 수 있는 추적 파일에 보관하려는 경우에 가장 적합합니다.

트리거 – DML(선택 제외)을 캡처하여 데이터베이스 어딘가에 저장하려는 경우에 가장 적합합니다.

쿼리 이력은 시스템뷰를 사용하여 표시할 수 있습니다.

  1. sys.dm_exec_module_module
  2. sys.dm_exec_sql_text
  3. sys.dm_exec_module_plan

예를 들어, 다음 조회를 사용합니다.

select  top(100)
        creation_time,
        last_execution_time,
        execution_count,
        total_worker_time/1000 as CPU,
        convert(money, (total_worker_time))/(execution_count*1000)as [AvgCPUTime],
        qs.total_elapsed_time/1000 as TotDuration,
        convert(money, (qs.total_elapsed_time))/(execution_count*1000)as [AvgDur],
        total_logical_reads as [Reads],
        total_logical_writes as [Writes],
        total_logical_reads+total_logical_writes as [AggIO],
        convert(money, (total_logical_reads+total_logical_writes)/(execution_count + 0.0)) as [AvgIO],
        [sql_handle],
        plan_handle,
        statement_start_offset,
        statement_end_offset,
        plan_generation_num,
        total_physical_reads,
        convert(money, total_physical_reads/(execution_count + 0.0)) as [AvgIOPhysicalReads],
        convert(money, total_logical_reads/(execution_count + 0.0)) as [AvgIOLogicalReads],
        convert(money, total_logical_writes/(execution_count + 0.0)) as [AvgIOLogicalWrites],
        query_hash,
        query_plan_hash,
        total_rows,
        convert(money, total_rows/(execution_count + 0.0)) as [AvgRows],
        total_dop,
        convert(money, total_dop/(execution_count + 0.0)) as [AvgDop],
        total_grant_kb,
        convert(money, total_grant_kb/(execution_count + 0.0)) as [AvgGrantKb],
        total_used_grant_kb,
        convert(money, total_used_grant_kb/(execution_count + 0.0)) as [AvgUsedGrantKb],
        total_ideal_grant_kb,
        convert(money, total_ideal_grant_kb/(execution_count + 0.0)) as [AvgIdealGrantKb],
        total_reserved_threads,
        convert(money, total_reserved_threads/(execution_count + 0.0)) as [AvgReservedThreads],
        total_used_threads,
        convert(money, total_used_threads/(execution_count + 0.0)) as [AvgUsedThreads],
        case 
            when sql_handle IS NULL then ' '
            else(substring(st.text,(qs.statement_start_offset+2)/2,(
                case
                    when qs.statement_end_offset =-1 then len(convert(nvarchar(MAX),st.text))*2      
                    else qs.statement_end_offset    
                end - qs.statement_start_offset)/2  ))
        end as query_text,
        db_name(st.dbid) as database_name,
        object_schema_name(st.objectid, st.dbid)+'.'+object_name(st.objectid, st.dbid) as [object_name],
        sp.[query_plan]
from sys.dm_exec_query_stats as qs with(readuncommitted)
cross apply sys.dm_exec_sql_text(qs.[sql_handle]) as st
cross apply sys.dm_exec_query_plan(qs.[plan_handle]) as sp
WHERE st.[text] LIKE '%query%'

현재 실행 중인 쿼리는 다음 스크립트를 사용하여 확인할 수 있습니다.

select ES.[session_id]
      ,ER.[blocking_session_id]
      ,ER.[request_id]
      ,ER.[start_time]
      ,DateDiff(second, ER.[start_time], GetDate()) as [date_diffSec]
      , COALESCE(
                    CAST(NULLIF(ER.[total_elapsed_time] / 1000, 0) as BIGINT)
                   ,CASE WHEN (ES.[status] <> 'running' and isnull(ER.[status], '')  <> 'running') 
                            THEN  DATEDIFF(ss,0,getdate() - nullif(ES.[last_request_end_time], '1900-01-01T00:00:00.000'))
                    END
                ) as [total_time, sec]
      , CAST(NULLIF((CAST(ER.[total_elapsed_time] as BIGINT) - CAST(ER.[wait_time] AS BIGINT)) / 1000, 0 ) as bigint) as [work_time, sec]
      , CASE WHEN (ER.[status] <> 'running' AND ISNULL(ER.[status],'') <> 'running') 
                THEN  DATEDIFF(ss,0,getdate() - nullif(ES.[last_request_end_time], '1900-01-01T00:00:00.000'))
        END as [sleep_time, sec] --Время сна в сек
      , NULLIF( CAST((ER.[logical_reads] + ER.[writes]) * 8 / 1024 as numeric(38,2)), 0) as [IO, MB]
      , CASE  ER.transaction_isolation_level
        WHEN 0 THEN 'Unspecified'
        WHEN 1 THEN 'ReadUncommited'
        WHEN 2 THEN 'ReadCommited'
        WHEN 3 THEN 'Repetable'
        WHEN 4 THEN 'Serializable'
        WHEN 5 THEN 'Snapshot'
        END as [transaction_isolation_level_desc]
      ,ER.[status]
      ,ES.[status] as [status_session]
      ,ER.[command]
      ,ER.[percent_complete]
      ,DB_Name(coalesce(ER.[database_id], ES.[database_id])) as [DBName]
      , SUBSTRING(
                    (select top(1) [text] from sys.dm_exec_sql_text(ER.[sql_handle]))
                  , ER.[statement_start_offset]/2+1
                  , (
                        CASE WHEN ((ER.[statement_start_offset]<0) OR (ER.[statement_end_offset]<0))
                                THEN DATALENGTH ((select top(1) [text] from sys.dm_exec_sql_text(ER.[sql_handle])))
                             ELSE ER.[statement_end_offset]
                        END
                        - ER.[statement_start_offset]
                    )/2 +1
                 ) as [CURRENT_REQUEST]
      ,(select top(1) [text] from sys.dm_exec_sql_text(ER.[sql_handle])) as [TSQL]
      ,(select top(1) [objectid] from sys.dm_exec_sql_text(ER.[sql_handle])) as [objectid]
      ,(select top(1) [query_plan] from sys.dm_exec_query_plan(ER.[plan_handle])) as [QueryPlan]
      ,NULL as [event_info]--(select top(1) [event_info] from sys.dm_exec_input_buffer(ES.[session_id], ER.[request_id])) as [event_info]
      ,ER.[wait_type]
      ,ES.[login_time]
      ,ES.[host_name]
      ,ES.[program_name]
      ,cast(ER.[wait_time]/1000 as decimal(18,3)) as [wait_timeSec]
      ,ER.[wait_time]
      ,ER.[last_wait_type]
      ,ER.[wait_resource]
      ,ER.[open_transaction_count]
      ,ER.[open_resultset_count]
      ,ER.[transaction_id]
      ,ER.[context_info]
      ,ER.[estimated_completion_time]
      ,ER.[cpu_time]
      ,ER.[total_elapsed_time]
      ,ER.[scheduler_id]
      ,ER.[task_address]
      ,ER.[reads]
      ,ER.[writes]
      ,ER.[logical_reads]
      ,ER.[text_size]
      ,ER.[language]
      ,ER.[date_format]
      ,ER.[date_first]
      ,ER.[quoted_identifier]
      ,ER.[arithabort]
      ,ER.[ansi_null_dflt_on]
      ,ER.[ansi_defaults]
      ,ER.[ansi_warnings]
      ,ER.[ansi_padding]
      ,ER.[ansi_nulls]
      ,ER.[concat_null_yields_null]
      ,ER.[transaction_isolation_level]
      ,ER.[lock_timeout]
      ,ER.[deadlock_priority]
      ,ER.[row_count]
      ,ER.[prev_error]
      ,ER.[nest_level]
      ,ER.[granted_query_memory]
      ,ER.[executing_managed_code]
      ,ER.[group_id]
      ,ER.[query_hash]
      ,ER.[query_plan_hash]
      ,EC.[most_recent_session_id]
      ,EC.[connect_time]
      ,EC.[net_transport]
      ,EC.[protocol_type]
      ,EC.[protocol_version]
      ,EC.[endpoint_id]
      ,EC.[encrypt_option]
      ,EC.[auth_scheme]
      ,EC.[node_affinity]
      ,EC.[num_reads]
      ,EC.[num_writes]
      ,EC.[last_read]
      ,EC.[last_write]
      ,EC.[net_packet_size]
      ,EC.[client_net_address]
      ,EC.[client_tcp_port]
      ,EC.[local_net_address]
      ,EC.[local_tcp_port]
      ,EC.[parent_connection_id]
      ,EC.[most_recent_sql_handle]
      ,ES.[host_process_id]
      ,ES.[client_version]
      ,ES.[client_interface_name]
      ,ES.[security_id]
      ,ES.[login_name]
      ,ES.[nt_domain]
      ,ES.[nt_user_name]
      ,ES.[memory_usage]
      ,ES.[total_scheduled_time]
      ,ES.[last_request_start_time]
      ,ES.[last_request_end_time]
      ,ES.[is_user_process]
      ,ES.[original_security_id]
      ,ES.[original_login_name]
      ,ES.[last_successful_logon]
      ,ES.[last_unsuccessful_logon]
      ,ES.[unsuccessful_logons]
      ,ES.[authenticating_database_id]
      ,ER.[sql_handle]
      ,ER.[statement_start_offset]
      ,ER.[statement_end_offset]
      ,ER.[plan_handle]
      ,NULL as [dop]--ER.[dop]
      ,coalesce(ER.[database_id], ES.[database_id]) as [database_id]
      ,ER.[user_id]
      ,ER.[connection_id]
from sys.dm_exec_requests ER with(readuncommitted)
right join sys.dm_exec_sessions ES with(readuncommitted)
on ES.session_id = ER.session_id 
left join sys.dm_exec_connections EC  with(readuncommitted)
on EC.session_id = ES.session_id
where ER.[status] in ('suspended', 'running', 'runnable')
or exists (select top(1) 1 from sys.dm_exec_requests as ER0 where ER0.[blocking_session_id]=ES.[session_id])

이 요청은 모든 활성 요청과 활성 요청을 명시적으로 차단하는 모든 요청을 표시합니다.

이러한 스크립트 및 기타 유용한 스크립트는 모두 SRV 데이터베이스에 표현으로 구현되어 자유롭게 배포됩니다.예를 들어 첫 번째 스크립트는 뷰 [inf]에서 가져옵니다.[vBigQuery], 그리고 두 번째가 뷰 [inf]에서 나왔습니다.[vRequests]

쿼리 이력을 위한 다양한 서드파티 솔루션도 있습니다.Dbeaver:의 Query ManagerSSMS에 내장된 SQL ToolsQuery Execution History를 사용합니다.

필요에 따라 SQL Profiler별로 SQL 쿼리를 감시할 수 있습니다.

시스템은 이러한 방식으로 쿼리를 기록하지 않습니다.미리 이 작업을 수행할 경우 SQL Profiler를 사용하여 Profiler 실행 중에 들어오는 내용을 기록하고 쿼리를 추적할 수 있습니다.

다른 사용자가 지적했듯이 SQL Profiler를 사용할 수도 있지만 sp_trace_* 시스템 스토어드 프로시저를 통해 SQL Profiler의 기능을 활용할 수도 있습니다.예를 들어 이 SQL 스니펫은 (적어도 2000에서는 SQL 2008과 동일하다고 생각합니다만, 다시 한 번 확인해야 합니다.RPC:Completed ★★★★★★★★★★★★★★★★★」SQL:BatchCompleted실행하는 데 10초 이상 걸리는 모든 쿼리에 대한 이벤트 및 나중에 SQL 프로파일러에서 열 수 있는 트레이스 파일에 출력을 저장합니다.

DECLARE @TraceID INT
DECLARE @ON BIT
DECLARE @RetVal INT
SET @ON = 1

exec @RetVal = sp_trace_create @TraceID OUTPUT, 2, N'Y:\TraceFile.trc'
print 'This trace is Trace ID = ' + CAST(@TraceID AS NVARCHAR)
print 'Return value = ' + CAST(@RetVal AS NVARCHAR)
-- 10 = RPC:Completed
exec sp_trace_setevent @TraceID, 10, 1, @ON     -- Textdata
exec sp_trace_setevent @TraceID, 10, 3, @ON     -- DatabaseID
exec sp_trace_setevent @TraceID, 10, 12, @ON        -- SPID
exec sp_trace_setevent @TraceID, 10, 13, @ON        -- Duration
exec sp_trace_setevent @TraceID, 10, 14, @ON        -- StartTime
exec sp_trace_setevent @TraceID, 10, 15, @ON        -- EndTime

-- 12 = SQL:BatchCompleted
exec sp_trace_setevent @TraceID, 12, 1, @ON     -- Textdata
exec sp_trace_setevent @TraceID, 12, 3, @ON     -- DatabaseID
exec sp_trace_setevent @TraceID, 12, 12, @ON        -- SPID
exec sp_trace_setevent @TraceID, 12, 13, @ON        -- Duration
exec sp_trace_setevent @TraceID, 12, 14, @ON        -- StartTime
exec sp_trace_setevent @TraceID, 12, 15, @ON        -- EndTime

-- Filter for duration [column 13] greater than [operation 2] 10 seconds (= 10,000ms)
declare @duration bigint
set @duration = 10000
exec sp_trace_setfilter @TraceID, 13, 0, 2, @duration

Books Online에서 각 트레이스 이벤트, 컬럼 등의 ID를 찾을 수 있습니다.sp_trace_create, sp_trace_seteventsp_trace_setfiler sprocs를 검색하기만 하면 됩니다.다음으로 트레이스를 다음과 같이 제어할 수 있습니다.

exec sp_trace_setstatus 15, 0       -- Stop the trace
exec sp_trace_setstatus 15, 1       -- Start the trace
exec sp_trace_setstatus 15, 2       -- Close the trace file and delete the trace settings

...여기서 '15'는 트레이스 ID입니다(위의 첫 번째 스크립트가 꺼낸 sp_trace_create에서 보고).

어떤 트레이스가 동작하고 있는지를 확인할 수 있습니다.

select * from ::fn_trace_getinfo(default)

주의점은 이것뿐입니다.시스템에 부하가 얼마나 걸릴지 알 수 없습니다.다만, 「일부」의 크기는, 서버의 사용 상황에 따라서 다릅니다.

여기 계신 모든 분들의 답변에 경의를 표합니다.

이 스크립트는 SQL에 영향을 미치는 상위 20개의 쿼리를 찾는 방법을 보여 줍니다.

select top 20 dest.text, deqs.execution_count, deqs.total_elapsed_time, deqs.total_worker_time,
(deqs.total_elapsed_time / deqs.execution_count) as 'avg_elapse_time',
(deqs.total_worker_time / deqs.execution_count) as 'avg_worker_time'
from sys.dm_exec_query_stats as deqs
CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) as dest
where deqs. last_execution_time >= '2021-09-27 16:00' /* YOUR DATE AND TIME HERE*/
order by 'avg_elapse_time' desc

트레이스 프로파일러가 유효하게 되어 있지 않다SQL 서버상의 애플리케이션액티비티를 트레이스 하려면 , 다음의 쿼리를 사용합니다.이 메서드는 DMV 대신 Query Store(SQL Server 2016+)를 사용합니다.이를 통해 이력 데이터를 더 잘 조사할 수 있을 뿐만 아니라 더 빠른 조회도 할 수 있습니다.sp_who/sp_whoisactive에서는 캡처할 수 없는 단기 쿼리를 캡처하는 것이 매우 효율적입니다.

/* Adjust script to your needs.
    Run full script (F5) -> Interact with UI -> Run full script again (F5)
    Output will contain the queries completed in that timeframe.
*/

/* Requires Query Store to be enabled:
    ALTER DATABASE <db> SET QUERY_STORE = ON
    ALTER DATABASE <db> SET QUERY_STORE (OPERATION_MODE = READ_WRITE, MAX_STORAGE_SIZE_MB = 100000)
*/

USE <db> /* Select your DB */

IF OBJECT_ID('tempdb..#lastendtime') IS NULL
    SELECT GETUTCDATE() AS dt INTO #lastendtime
ELSE IF NOT EXISTS (SELECT * FROM #lastendtime)
    INSERT INTO #lastendtime VALUES (GETUTCDATE()) 

;WITH T AS (
SELECT 
    DB_NAME() AS DBName
    , s.name + '.' + o.name AS ObjectName
    , qt.query_sql_text
    , rs.runtime_stats_id
    , p.query_id
    , p.plan_id
    , CAST(p.last_execution_time AS DATETIME) AS last_execution_time
    , CASE WHEN p.last_execution_time > #lastendtime.dt THEN 'X' ELSE '' END AS New
    , CAST(rs.last_duration / 1.0e6 AS DECIMAL(9,3)) last_duration_s
    , rs.count_executions
    , rs.last_rowcount
    , rs.last_logical_io_reads
    , rs.last_physical_io_reads
    , q.query_parameterization_type_desc
FROM (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY plan_id, runtime_stats_id ORDER BY runtime_stats_id DESC) AS recent_stats_in_current_priod
    FROM sys.query_store_runtime_stats 
    ) AS rs
INNER JOIN sys.query_store_runtime_stats_interval AS rsi ON rsi.runtime_stats_interval_id = rs.runtime_stats_interval_id
INNER JOIN sys.query_store_plan AS p ON p.plan_id = rs.plan_id
INNER JOIN sys.query_store_query AS q ON q.query_id = p.query_id
INNER JOIN sys.query_store_query_text AS qt ON qt.query_text_id = q.query_text_id
LEFT OUTER JOIN sys.objects AS o ON o.object_id = q.object_id
LEFT OUTER JOIN sys.schemas AS s ON s.schema_id = o.schema_id
CROSS APPLY #lastendtime
WHERE rsi.start_time <= GETUTCDATE() AND GETUTCDATE() < rsi.end_time
    AND recent_stats_in_current_priod = 1
    /* Adjust your filters: */
    -- AND (s.name IN ('<myschema>') OR s.name IS NULL)
UNION
SELECT NULL,NULL,NULL,NULL,NULL,NULL,dt,NULL,NULL,NULL,NULL,NULL,NULL, NULL
FROM #lastendtime
)
SELECT * FROM T
WHERE T.query_sql_text IS NULL OR T.query_sql_text NOT LIKE '%#lastendtime%' -- do not show myself
ORDER BY last_execution_time DESC

TRUNCATE TABLE #lastendtime
INSERT INTO #lastendtime VALUES (GETUTCDATE()) 
SELECT deqs.last_execution_time AS [Time], dest.text AS [Query], dest.*
FROM sys.dm_exec_query_stats AS deqs
CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) AS dest
WHERE dest.dbid = DB_ID('msdb')
ORDER BY deqs.last_execution_time DESC

쿼리가 실행된 날짜와 시간이 표시됩니다.

SMSS를 통해 실행한 쿼리의 이력을 원하는 경우.

SSMSPlus를 사용해 보는 것이 좋습니다.

https://github.com/akarzazi/SSMSPlus

이 기능은 SSMS에 처음부터 존재하지 않습니다.

SSMS 18 이상이 필요합니다.

면책사항 : 제가 작성자입니다.

아래 SQL 쿼리는 단순한 쿼리 로그를 표시할 수 있습니다.

SELECT last_execution_time, text
FROM sys.dm_exec_query_stats stats
CROSS APPLY sys.dm_exec_sql_text(stats.sql_handle) 
ORDER BY last_execution_time

다음과 같이 표시됩니다.

여기에 이미지 설명 입력

또한 다음 SQL 쿼리는 단순한 트랜잭션 쿼리 로그를 표시할 수 있습니다.

SELECT Operation, [Begin Time], [End Time] 
FROM fn_dblog(NULL,NULL)

다음과 같이 표시됩니다.

여기에 이미지 설명 입력

또한 단순 쿼리 로그와 단순 트랜잭션 쿼리 로그를 함께 표시하기 위한 SQL 쿼리는 알 수 없습니다.

관리 스튜디오를 사용하는 경우 "저장할 때마다 자동으로 스크립트 생성"을 사용할 수 있습니다.이것은 확실히 로깅이 아닙니다.도움이 되는지 확인합니다.;)

관심 있는 쿼리가 간헐적으로 실패하는 동적 쿼리인 경우 동적 문이 생성될 때 SQL과 날짜 및 사용자를 테이블에 기록할 수 있습니다.특정 프로그래밍이 필요하고 처리 시간이 조금 걸리기 때문에 케이스 바이 케이스로 실행되므로 가장 우려되는 몇 가지 쿼리에 대해서만 실행해 주십시오.그러나 특정 스테이트먼트의 로그를 실행하면 한 달에 한 번만 실패하는 이유를 알 수 있습니다.동적 쿼리는 완전히 테스트하기 어렵기 때문에 특정 입력값 중 하나라도 제대로 작동하지 않을 수 있습니다. SQL 생성 시 이 로깅을 수행하는 것이 구축된 SQL에 구체적으로 무엇이 포함되었는지 확인하는 가장 좋은 방법입니다.

즉시 사용할 수 있는 방법은 AutoHotKey에서 솔루션을 스크립팅하는 것입니다.나는 이것을 사용하고, 완벽하지는 않지만, 일하고 무료입니다.기본적으로 이 스크립트는 선택한 SQL을 SSMS(+)CTRLC에 복사하고 데이터 스탬프 SQL 파일을 저장한 후 강조 표시된 F5쿼리를 실행하는 단축키를 ++SHIFTR에 할당합니다().AHK 스크립트에 익숙하지 않은 경우 선두 세미콜론은 코멘트입니다.

;CTRL+SHIFT+R to run a query that is first saved off
^+r::
;Copy
Send, ^c
; Set variables
EnvGet, HomeDir, USERPROFILE
FormatTime, DateString,,yyyyMMdd
FormatTime, TimeString,,hhmmss
; Make a spot to save the clipboard
FileCreateDir %HomeDir%\Documents\sqlhist\%DateString%
FileAppend, %Clipboard%, %HomeDir%\Documents\sqlhist\%DateString%\%TimeString%.sql
; execute the query
Send, {f5}
Return

가장 큰 제약사항은 이 스크립트가 키보드 바로 가기를 사용하지 않고 "실행"을 클릭하면 작동하지 않고 선택한 텍스트만 파일 전체가 저장되지 않는다는 것입니다.그러나 언제든지 스크립트를 수정하여 쿼리를 실행하고 복사/저장하기 전에 CTRLA모두(+)를 선택할 수 있습니다.

"파일 검색" 기능이 있는 최신 편집기를 사용하면 SQL 이력을 검색할 수 있습니다.또한 SQLite3 데이터베이스에 파일을 스크램핑하여 쿼리를 쿼리할 수도 있습니다.

언급URL : https://stackoverflow.com/questions/5299669/how-to-see-query-history-in-sql-server-management-studio

반응형