USE [master]
GO
CREATE LOGIN [YourDomain\ReadOnlyGroup] FROM WINDOWS WITH DEFAULT_DATABASE=[master], DEFAULT_LANGUAGE=[us_english]
GO
USE [yourDatabase]
GO
CREATE USER [YourDomain\ReadOnlyGroup] FOR LOGIN [YourDomain\ReadOnlyGroup]
GO
USE [yourDatabase]
GO
ALTER ROLE [db_datareader] ADD MEMBER [YourDomain\ReadOnlyGroup]
GO
接下来创建表格并添加最新/最后一个冻结间隔开始日期。我们将使用更新的日期,但根据需要进行调整。
USE master
GO
CREATE TABLE LastReadFreeze (LastFreezeDate date)
UPDATE LastReadFree
SET LastFreezeDate='2022-10-11'
DECLARE
@startDate date, --First day of a freeze interval
@endDate date, --Last day of a freeze interval; leave blank
@freezeInterval int = 2, --Number of days for a freeze interval -1
@freeReads int = 13 --Number of days between freeze inervals
--get the start date of the last freeze interval
SELECT @startDate=LastFreezeDate FROM LastReadFreeze
--set the end date based on freeze interval and
SELECT @endDate=DATEADD(Day,@freezeInterval, @startDate)
--check today against the freeze start and end dates
IF CAST(GETDATE() as date) BETWEEN @startDate and @endDate
BEGIN
--if today is between those dates, disable the login
IF (SELECT is_disabled FROM sys.server_principals WHERE name='YourDomain\ReadOnlyGroup')=0
ALTER LOGIN [YourDomain\ReadOnlyGroup] DISABLE
END
ELSE
BEGIN
--if today is not between those dates, check to see if it's time to set a new freeze interval based on end date of last freeze and the free reads
IF CAST(GETDATE() AS DATE) = DATEADD(Day,@freeReads,@endDate)
BEGIN
--reset the start date of the freeze interval if today matches end date of last interval plus free reads
UPDATE LastReadFreeze
SET LastFreezeDate=DATEADD(Day,@freeReads,@endDate)
--disable the login
IF (SELECT is_disabled FROM sys.server_principals WHERE name='YourDomain\ReadOnlyGroup')=0
ALTER LOGIN [YourDomain\ReadOnlyGroup] DISABLE
END
ELSE
BEGIN
--today is not in the freeze interval nor is it time to reset the freeze interval; ensure the login is enabled
IF (SELECT is_disabled FROM sys.server_principals WHERE name='YourDomain\ReadOnlyGroup')=1
ALTER LOGIN [YourDomain\ReadOnlyGroup] ENABLE
END
END
1条答案
按热度按时间2ledvvac1#
如果我理解你的问题,你想阻止用户在特定时间段访问数据,并且你想能够安排时间。这是一个奇怪的请求,但你最好的办法是为你想要管理访问权限的用户创建一个AD组。然后,您需要创建一个SQLAgent作业,以在指定的时间间隔内禁用该组。我会使用一个表格来跟踪“冻结”间隔,以使其影响尽可能小
创建您的登录名和用户
接下来创建表格并添加最新/最后一个冻结间隔开始日期。我们将使用更新的日期,但根据需要进行调整。
下面是根据冻结间隔验证今天并根据需要重置的代码。您可以将其作为存储过程或内联使用。无论哪种方式,您都希望创建SQLAgent作业并将其安排为每天早上运行。