如何使用当前系统日期从nvarchar类型dob计算年龄 [英] how to calculate age from nvarchar type dob with current system date
本文介绍了如何使用当前系统日期从nvarchar类型dob计算年龄的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
hii ..所有
我是anil.i m in development ...我想计算不。在1到14岁之间的候选人。
在我的表中dob是nvarchar类型..
请帮助
提前感谢..
hii.. all
i m anil.i m new in development.. i want to calculate no. of candidates between 1 to 14 age.
in my table the dob is a nvarchar type..
please help
thanks in advance..
推荐答案
good想法是使用Date或datetime数据类型为这种类型使用nvarchar
good idea is to use Date , or datetime datatype for this type insted of using nvarchar
不要将日期存储为nvarchar
数据类型!使用正确的数据类型 [ ^ ]。
转换nvarchar数据类型,使用 CONVERT [ ^ ]功能和 DATEDIFF [ ^ ]来计算年龄。示例:
Do not store dates asnvarchar
data type! Use proper data type[^].
To convert nvarchar data type, use CONVERT[^] function and DATEDIFF[^] to calculate age. Example:
DECLARE @tmp TABLE (dob NVARCHAR(30))
INSERT INTO @tmp (dob)
VALUES('1974-06-13'), ('1999-08-16'), ('2002-02-18')
SELECT CONVERT(DATETIME, dob) AS dob, GETDATE() AS CurrentDate, DATEDIFF(yyyy, dob, GETDATE()) AS Age
FROM @tmp
如果 dob
字段存储数据,如 '13 -06-1974'
,如果当前服务器日期时间设置为 yyyy-MM-dd
,则转换将失败。在这种情况下,您需要使用 SET DATEFORMAT [ ^ ]命令。例如:
If the dob
field stores data like '13-06-1974'
, the conversion will fail if the current server date-time setting is yyyy-MM-dd
. In this case you need to change it by using SET DATEFORMAT[^] command. For example:
DECLARE @tmp TABLE (dob NVARCHAR(30))
INSERT INTO @tmp (dob)
VALUES('13-06-1974'), ('16-08-1999'), ('18-02-2002')
SET DATEFORMAT dmy;
SELECT CONVERT(DATETIME, dob) AS dob, GETDATE() AS CurrentDate, DATEDIFF(yyyy, dob, GETDATE()) AS Age
FROM @tmp
WHERE DATEDIFF(yyyy, dob, GETDATE()) BETWEEN 6 AND 14
[/ EDIT]
[/EDIT]
这篇关于如何使用当前系统日期从nvarchar类型dob计算年龄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文