[sql-server] T-SQL의 슬립 명령?

일정 시간 동안 절전 모드로 전환하기 위해 T-SQL 명령을 작성해야합니까? 웹 서비스를 비동기 적으로 작성하고 있으며 비동기 패턴이 실제로 확장 성을 높이기 위해 몇 가지 테스트를 실행할 수 있기를 원합니다. 느린 외부 서비스를 “모의”하기 위해 느리게 실행되지만 실제로는 많은 것을 처리하지 않는 스크립트로 SQL 서버를 호출 할 수 있기를 원합니다.



답변

상기 봐 WAITFOR의 명령.

예 :

-- wait for 1 minute
WAITFOR DELAY '00:01'

-- wait for 1 second
WAITFOR DELAY '00:00:01'

이 명령은 높은 정밀도를 허용하지만 GetTickCount에 의존하기 때문에 일반적인 컴퓨터에서는 10ms-16ms 내에서만 정확 합니다 . 예를 들어, 통화 는 전혀 기다리지 않을 것입니다.WAITFOR DELAY '00:00:00:001'


답변

WAITFOR DELAY 'HH:MM:SS'

이것이 기다릴 수있는 최대 시간은 23 시간 59 분 59 초라고 생각합니다.

스칼라 값 함수는 다음과 같습니다. 아래 함수는 초의 정수 매개 변수를 취한 다음 HH : MM : SS로 변환 EXEC sp_executesql @sqlcode하고 쿼리 명령을 사용하여 실행합니다. 아래 함수는 데모 용입니다. 스칼라 값 함수로 실제로는 적합하지 않습니다! 🙂

    CREATE FUNCTION [dbo].[ufn_DelayFor_MaxTimeIs24Hours]
    (
    @sec int
    )
    RETURNS
    nvarchar(4)
    AS
    BEGIN


    declare @hours int = @sec / 60 / 60
    declare @mins int = (@sec / 60) - (@hours * 60)
    declare @secs int = (@sec - ((@hours * 60) * 60)) - (@mins * 60)


    IF @hours > 23
    BEGIN
    select @hours = 23
    select @mins = 59
    select @secs = 59
    -- 'maximum wait time is 23 hours, 59 minutes and 59 seconds.'
    END


    declare @sql nvarchar(24) = 'WAITFOR DELAY '+char(39)+cast(@hours as nvarchar(2))+':'+CAST(@mins as nvarchar(2))+':'+CAST(@secs as nvarchar(2))+char(39)


    exec sp_executesql @sql

    return ''
    END

24 시간 이상 지연하려면 @Days 매개 변수를 사용하여 며칠 동안 가고 함수 실행 파일을 루프 안에 넣는 것이 좋습니다.

    Declare @Days int = 5
    Declare @CurrentDay int = 1

    WHILE @CurrentDay <= @Days
    BEGIN

    --24 hours, function will run for 23 hours, 59 minutes, 59 seconds per run.
    [ufn_DelayFor_MaxTimeIs24Hours] 86400

    SELECT @CurrentDay = @CurrentDay + 1
    END


답변

“시간”을 “대기”할 수도 있습니다.

    RAISERROR('Im about to wait for a certain time...', 0, 1) WITH NOWAIT
    WAITFOR TIME '16:43:30.000'
    RAISERROR('I waited!', 0, 1) WITH NOWAIT


답변

다음은 CommandTimeout을 테스트하기위한 매우 간단한 C # 코드입니다. 새로운 명령을 생성하여 2 초 동안 기다립니다. CommandTimeout을 1 초로 설정하면 실행할 때 예외가 표시됩니다. CommandTimeout을 0 또는 2보다 높은 값으로 설정하면 정상적으로 실행됩니다. 그런데 기본 CommandTimeout은 30 초입니다.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Data.SqlClient;

namespace ConsoleApplication1
{
  class Program
  {
    static void Main(string[] args)
    {
      var builder = new SqlConnectionStringBuilder();
      builder.DataSource = "localhost";
      builder.IntegratedSecurity = true;
      builder.InitialCatalog = "master";

      var connectionString = builder.ConnectionString;

      using (var connection = new SqlConnection(connectionString))
      {
        connection.Open();

        using (var command = connection.CreateCommand())
        {
          command.CommandText = "WAITFOR DELAY '00:00:02'";
          command.CommandTimeout = 1;

          command.ExecuteNonQuery();
        }
      }
    }
  }
}


답변