복붙노트

[SQL] SQL 서버 (TSQL) -이 병렬로 EXEC 문에 수 있습니까?

SQL

SQL 서버 (TSQL) -이 병렬로 EXEC 문에 수 있습니까?

SQL 서버 2008 R2

다음은 간단한 예이다 :

EXECUTE sp_executesql N'PRINT ''1st '' + convert(varchar, getdate(), 126) WAITFOR DELAY ''000:00:10'''
EXECUTE sp_executesql N'PRINT ''2nd '' + convert(varchar, getdate(), 126)'

첫 번째 문은 날짜를 인쇄 진행하기 전에 10 초 지연됩니다. 두 번째 문은 즉시 인쇄해야합니다.

T-SQL이 작동하는 방식은, 제 2 문은 첫째 완료 될 때까지 평가되지 않습니다. 내가 복사하여 새 쿼리 창에 붙여 넣을 경우, 즉시 실행됩니다.

문제는 내가 다른, 더 복잡한 일들이 모두 절차에 전달해야 할 변수, 진행해야한다는 것입니다.

내가 뭘하려고 수 있습니다 :

아마도 동적 작업의 몇 가지를 만들 수있는 방법은 무엇입니까?

어쨌든, 수동으로 문을 인쇄하고 복사 / 다른 세션에 붙여 넣기 할 필요없이이 작업을 수행 할 수있는 간단한 방법을 찾고 있어요.

대기없이 EXEC 할 수있는 방법은 병렬 / 있는가?

해결법

  1. ==============================

    1.예, 비동기 프로 시저 실행을 볼 수있는 방법이있다.

    예, 비동기 프로 시저 실행을 볼 수있는 방법이있다.

    그러나 기회는이 당신이 필요하지 않습니다이다. 당신이 롤백 의미가 병렬 작업이 거의 불가능하다 / 고려 거래를 고려 잠금 커밋 할 때 T-SQL은 데이터 액세스 언어합니다. 병렬 T-SQL은 각 요청이 독립적이며 작업간에 상관이없는 요청 큐와 인스턴스에 적용됩니다.

    당신이 없으며, 실제로 paralellized해야 할 수있는 일처럼 전혀 소리가 나지 않는다 설명합니다.

  2. ==============================

    2.당신은 당신이 그것을에 대한 문을 실행할 수 있도록 기록을 잠 그려면, 당신은 트랜잭션으로 그 문을 실행 할 수 있습니다.

    당신은 당신이 그것을에 대한 문을 실행할 수 있도록 기록을 잠 그려면, 당신은 트랜잭션으로 그 문을 실행 할 수 있습니다.

    병렬 SQL을 실행하려면 (지옥, 백그라운드에서 쉘 스크립트에서 "ISQL"를 실행하면 작동합니다) ++ 자바, C에서 별도의 스레드 / 프로세스 내에서 SQL을 실행하여, SQL 호출을 paralellize하기 위해, 펄, 또는 다른 프로그래밍 언어를 필요

  3. ==============================

    3.당신은 여전히 ​​병렬로 일을 실행하려는 잠재적 인 문제에 대해 위의 모든를 읽은 후, 당신은 아마 SQL 작업을 시도 할 경우이 같은 작업을 호출하여 실행 한 후, 다른 작업에 쿼리를 넣어

    당신은 여전히 ​​병렬로 일을 실행하려는 잠재적 인 문제에 대해 위의 모든를 읽은 후, 당신은 아마 SQL 작업을 시도 할 경우이 같은 작업을 호출하여 실행 한 후, 다른 작업에 쿼리를 넣어

    EXEC msdb..sp_start_job 'Job1'
    
    EXEC msdb..sp_start_job 'Job2' 
    
  4. ==============================

    4.이 서비스 브로커없이 기사 비동기 T-SQL 실행을 체크 아웃 가치가있을 수도 있습니다.

    이 서비스 브로커없이 기사 비동기 T-SQL 실행을 체크 아웃 가치가있을 수도 있습니다.

  5. ==============================

    5.SQL 에이전트 작업은 병렬로 실행할 수 TSQL에서 직접 생성 될 수있다. 레무스 Rusanu에 의한 대답은 몇 가지 단점과 함께이 언급 링크가 포함되어 있습니다.

    SQL 에이전트 작업은 병렬로 실행할 수 TSQL에서 직접 생성 될 수있다. 레무스 Rusanu에 의한 대답은 몇 가지 단점과 함께이 언급 링크가 포함되어 있습니다.

    또 다른 단점은 추가 보안 권한이 작업을 만드는 데 필요한 것입니다. 또한, 아래의 구현을 위해, 작업은 추가 작업 관리 권한을 가진 특정 사용자 + 로그인으로 실행해야합니다.

    내가 같은 작업을 지정하는 시스템 관리자 권한이 필요 생각하지만 다른 (안전) 사용자로 임의의 SQL을 실행할 수 있습니다.

    반환 @pJobIdHexOut이 필요한 경우 작업을 중지 할 수 있습니다.

    create function Common.ufn_JobIdFromHex(
        @pJobIdBinary binary(16)
        )    
        returns varchar(100) as
    /*---------------------------------------------------------------------------------------------------------------------
        Purpose:   Convert the binary represenation of the job_id into the job_id string that can be used in queries 
                   against msdb.dbo.sysjobs.
    
                    http://stackoverflow.com/questions/68677/how-can-i-print-a-binary-value-as-hex-in-tsql
                    http://stackoverflow.com/questions/3604603 
                    MsgBoards
    
        Modified    By              Description
        ----------  --------------  ---------------------------------------------------------------------------------------
        2014.08.22  crokusek        Initial version, http://stackoverflow.com/questions/3604603 and MsgBoards.
      ---------------------------------------------------------------------------------------------------------------------*/ 
    begin 
    
        -- Convert from binary and strip off the '0x'.
        --
        declare
            @jobIdHex varchar(100) = replace(convert(varchar(300), @pJobIdBinary, 1), '0x', ''); 
    
        -- The endianness appears to be backwards and there are dashes needed.                
        --
        return
            substring(@jobIdHex,7,2) +
            substring(@jobIdHex,5,2) +
            substring(@jobIdHex,3,2) +
            substring(@jobIdHex,1,2) +
            '-' +
            substring(@jobIdHex,11,2) +
            substring(@jobIdHex,9,2) +
            '-' +
            substring(@jobIdHex,15,2) +
            substring(@jobIdHex,13,2) +
            '-' +
            substring(@jobIdHex,17,4) +
            '-' +
            substring(@jobIdHex,21,12);  
    end
    go
    
    create proc [Common].[usp_CreateExecuteOneTimeBackgroundJob] 
        @pJobNameKey          varchar(100),     -- Caller should ensure uniqueness to avoid a violation
        @pJobDescription      varchar(1000),
        @pSql                 nvarchar(max),
        @pJobIdHexOut         varchar(100) = null out, -- JobId as Hex string. For SqlServer 2014 binary(16) = varchar(64)
        @pDebug               bit = 0  -- True to include print messages
    --
    with execute as 'TSqlBackgroundJobOwner' -- requires special permissions (See below)
    as
    /*---------------------------------------------------------------------------------------------------------------------
        Purpose:  Create a one time background job and launch it immediately.  The job is owned by the "execute as" UserName 
    
                  Caller must ensure the @pSql argument is safe.
    
    Required Permissions for "execute as" user:
    
            -- User must be created with associated login (w/ deny connect).
    
            use [msdb];
            create user [$UserName$] for login [$LoginName$];
            alter role [SQLAgentUserRole] add member [$UserName$];
            alter role [SQLAgentReaderRole] add member [$UserName$];
            alter role [SQLAgentOperatorRole] add member [$UserName$];
            grant select on dbo.sysjobs to [$UserName$];
            grant select on dbo.sysjobactivity to [$UserName$];',
    
            use [Master];
            create user [$UserName$] for login [$LoginName$];
            grant execute on xp_sqlagent_is_starting to [$UserName$];
            grant execute on xp_sqlagent_notify to [$UserName$];';
    
    
        Modified    By           Description
        ----------  -----------  ------------------------------------------------------------------------------------------
        2014.08.22  crokusek     Initial version   
        2015.12.22  crokusek     Use the SP caller as the job owner (removed the explicit setting of the job owner).
      ---------------------------------------------------------------------------------------------------------------------*/
    begin try       
    
        declare
            @usp                  varchar(100) = object_name(@@procid),
            @currentDatabase      nvarchar(100) = db_name(),
            @jobId                binary(16),        
            @jobOwnerLogin        nvarchar(100);
    
        set xact_abort on;    -- ensure transaction is aborted on non-catchables like client timeout, etc.
        begin transaction
    
            exec msdb.dbo.sp_add_job 
                @job_name=@pJobNameKey,
                    @enabled=1, 
                    @notify_level_eventlog=0, 
                    @notify_level_email=2, 
                    @notify_level_netsend=2, 
                    @notify_level_page=2, 
                    @delete_level=3, 
                    @description=@pJobDescription,
                    @category_name=N'Database Maintenance',
                -- If not overridden then the the current login is the job owner
                --@owner_login_name=@jobOwnerLogin,  -- Requires sysadmin to set this so avoiding.
                @job_id = @jobId output;
    
            -- Get the job_id string of the jobId (special format)
            --
            set @pJobIdHexOut = Common.ufn_JobIdFromHex(@jobId);
    
            if (@pDebug = 1)
            begin
                print 'JobId: ' + @pJobIdHexOut;
                print 'Sql: ' + @pSql;
            end
    
            exec msdb.dbo.sp_add_jobserver @job_id=@jobId; -- default is local server
    
            exec msdb.dbo.sp_add_jobstep 
                @job_id=@jobId, 
                @step_name=N'One-Time Job Step 1', 
                    @step_id=1, 
                @command=@pSql,
                    @database_name=@currentDatabase,
                    @cmdexec_success_code=0, 
                    @on_success_action=1, 
                    @on_fail_action=2, 
                    @retry_attempts=0, 
                    @retry_interval=0, 
                    @os_run_priority=0,
                @subsystem=N'TSQL', 
                    @flags=0
                ;
    
              declare
                  @startResult int;                    
    
              exec @startResult = msdb.dbo.sp_start_job 
                  @job_id = @jobId;
    
          -- End the transaction
          --
          if (@startResult != 0)          
              raiserror('Unable to start the job', 16, 1);  -- causes rollback in catch block
          else
              commit;   -- Success
    
    end try
    begin catch
        declare        
            @CatchingUsp  varchar(100) = object_name(@@procid);    
    
        if (xact_state() = -1)
            rollback;
    
        --exec Common.usp_Log
        --    @pMethod = @CatchingUsp;
    
        --exec Common.usp_RethrowError
        --    @pCatchingMethod = @CatchingUsp;
    end catch
    go
    
  6. ==============================

    6.당신은 병렬로 실행이 작업이있는 SSIS를 만들 수 있습니다. 그런 다음이 SSIS를 호출하는 예약되지 않은 에이전트 작업을합니다. 당신은 마지막으로 sp_start_job를 사용하여이 예정되지 않은 에이전트 작업을 실행할 수 있습니다.

    당신은 병렬로 실행이 작업이있는 SSIS를 만들 수 있습니다. 그런 다음이 SSIS를 호출하는 예약되지 않은 에이전트 작업을합니다. 당신은 마지막으로 sp_start_job를 사용하여이 예정되지 않은 에이전트 작업을 실행할 수 있습니다.

  7. from https://stackoverflow.com/questions/4571823/sql-server-tsql-is-it-possible-to-exec-statements-in-parallel by cc-by-sa and MIT license