简体   繁体   English

SQL Server 2008-处理日期-周窗口

[英]sql server 2008 - manipulating dates - week window

If I want to make sure an operation can only be done once a week by a user, what is an efficient way to do it? 如果我想确保用户每周只能进行一次操作,那么有效的方法是什么? If a user has carried out that operation on Friday, then he can still do it on Tuesday, because it's "next" week. 如果用户在星期五进行了该操作,那么他仍可以在星期二进行操作,因为这是“下一周”。

Your users do not have direct access to your database server, there is a UI through which this operation is performed... correct? 您的用户没有对数据库服务器的直接访问权,有一个执行该操作的用户界面...对吗?

Therefore, the efficient way is to have an "OperationLastPerformed" (of type `datetime) column in your table and to populate that field when the operation is performed. 因此,有效的方法是在表中具有“ OperationLastPerformed”(日期时间类型)列,并在执行操作时填充该字段。

At that point, which ever programming language is used for your UI, it will be easy (and proper) to enforce that piece of business logic from your code... 到那时,无论哪种编程语言都用于您的UI,从代码中强制执行那部分业务逻辑都是很容易的(也是正确的)...

If that is not acceptable and this must be done from the backend you could create a trigger that would check the "OperationLastPerformed" field before commiting the record and if the datetime is within current week rollback the commit... 如果这是不可接受的,并且必须从后端完成,则可以创建一个触发器,该触发器将在提交记录之前检查“ OperationLastPerformed”字段,并且如果datetime在当前一周内回滚,则提交...

In a real general sense you can do this. 从真正的一般意义上讲,您可以执行此操作。 It assumes a History Table with at least one column [Last_Date_Ran] 假设历史记录表至少包含一列[Last_Date_Ran]

  1. Begin process 开始过程
  2. check the history table for a date within current Sun-Sat 检查历史记录表中当前Sun-Sat内的日期
  3. If a record extists in step 2 exit else perform process. 如果在步骤2中存在记录,则退出,否则执行过程。

Create a table that stores a history of user actions: 创建一个表来存储用户操作的历史记录:

CREATE TABLE UserActions (
   userId int,
   weekOfYear int,
   year int
)

To check if the user has performed an action during the same week, you can use the DATEPART function to determine the week: 要检查用户是否在同一周内执行了某项操作,可以使用DATEPART函数确定一周:

IF EXISTS (SELECT * FROM UserActions WHERE userId = @userID and weekOfYear = DATEPART(isowk, GetDate() AND year = Year(GetDate() ) IF EXISTS (SELECT * FROM UserActions WHERE userId = @userID and weekOfYear = DATEPART(isowk, GetDate() AND year = Year(GetDate() ))

If that returns NULL, the user hasn't performed any actions in the current week. 如果返回NULL,则表示用户在当前星期未执行任何操作。 Then, you could insert a row after the action is performed. 然后,您可以在执行操作后插入一行。

INSERT INTO UserActions (userId, weekOfYear int, year) 
VALUES (@userId, DATEPART(isowk, GetDate(), Year(GetDate())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM