如何自动将 1 年日期添加到 SQL Server 中的现有日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9212958/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 14:20:02  来源:igfitidea点击:

How automatically add 1 year date to an existing date in SQL Server

sqlsql-servertsql

提问by Rahmat

I have a task to automatically bill all registered patients in PatientsInfotable an Annual Bill of N2,500 base on the DateCreatedcolumn.

我有一项任务是根据列自动向PatientsInfo表中的所有注册患者收取 N2,500 的年度账单DateCreated

Certainly I will use a stored procedure to insert these records into the PatientDebittable and create a SQL Job to perform this procedure.

当然,我会使用存储过程将这些记录插入到PatientDebit表中,并创建一个 SQL 作业来执行此过程。

How will I select *patients in PatientsInfotable where DateCreatedis now 1 yr old for me to insert into another table PatientDebit.

我将如何select *在现在 1 岁的PatientsInfo表中DateCreated插入患者以插入到另一个表中PatientDebit

I have my algorithm like this:

我有这样的算法:

  1. select date of registration for patients from PatientsInfotable
  2. Add 1 year to their DateCreated
  3. Is date added today? if yes,
  4. Insert record into PatientDebittable with the bill of N2,500
  5. If no, do nothing.
  1. PatientsInfo表中 选择患者的注册日期
  2. 将 1 年添加到他们的 DateCreated
  3. 日期添加到今天了吗?如果是,
  4. 将记录插入PatientDebit带有 N2,500 账单的表中
  5. 如果没有,什么都不做。

Please how do I write the script?

请问怎么写脚本啊?

回答by JScoobyCed

Use DATEADD, i.e.:

使用 DATEADD,即:

SELECT DATEADD(year, 1, '2006-08-30')

Ref.: http://msdn.microsoft.com/en-us/library/ms186819.aspx

参考:http: //msdn.microsoft.com/en-us/library/ms186819.aspx

回答by Johann

Assuming the columns of the 2 tables are the same:

假设两个表的列是相同的:

INSERT INTO PatientDebit
SELECT * from PatientsInfo WHERE DateCreated<DATEADD(year, -1, GETDATE())

Make sure you have an index on DateCreatedif PatientsInfohas a lot of records as it could potentially be slow otherwise

DateCreated如果PatientsInfo有很多记录,请确保您有一个索引,否则可能会很慢

回答by iefpw

there should be .add or addyear() function in sql. You add like .add(year, day, month). Read upon sql datetime add year, month and seconds. It is pretty straightforward. It is just like c#.

sql 中应该有 .add 或 addyear() 函数。你添加像 .add(year, day, month)。读取 sql datetime 添加年、月和秒。这很简单。它就像c#。

Dateadd(info). now time is. getdate().

日期添加(信息)。现在是时候了。获取日期()。