有没有办法写一个T-SQL命令,只是让它睡眠一段时间?我正在异步地编写一个web服务,我希望能够运行一些测试,看看异步模式是否真的会使它更具可伸缩性。为了“模拟”速度较慢的外部服务,我希望能够使用运行较慢的脚本调用SQL服务器,但实际上并没有处理大量的东西。
看一下WAITFOR命令。
E.g.
-- wait for 1 minute
WAITFOR DELAY '00:01'
-- wait for 1 second
WAITFOR DELAY '00:00:01'
这个命令可以提供很高的精度,但在典型机器上只能精确到10ms - 16ms,因为它依赖于GetTickCount。因此,例如,调用WAITFOR DELAY '00:00:00:001'很可能导致根本没有等待。
下面是一段非常简单的c#代码,用于测试CommandTimeout。 它创建一个新命令,该命令将等待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();
}
}
}
}
}
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
你也可以“WAITFOR”一个“TIME”:
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
推荐文章
- 等待一个无效的异步方法
- 使用Python请求的异步请求
- 如何将SQL Azure数据库复制到本地开发服务器?
- SQL Server 2008不能用新创建的用户登录
- PHP中的异步shell执行器
- 暂停Python程序的正确方法
- Python中的异步方法调用?
- SQL Server中User和Login的区别
- 在参数声明中,varchar(MAX)的大小是多少?
- 数据库性能调优有哪些资源?
- 为两列的组合添加唯一的约束
- SQL Server的隐藏特性
- 方括号[]在sql语句中有什么用?
- 对象'DF__*'依赖于列'*' -将int改为double
- 如何根据出生日期和getDate()计算年龄(以年为单位)