Sql Server类型转换,Sql Server函数

CONVERT(数据类型, 表达式, 样式) --样式可以没有

CAST(表达式 as 数据类型)

cs 复制代码
select StudentName + '的出生日期是:' + cast(DateOfBirth as varchar(50)) as '学生信息'
from Students;
select StudentName + '的出生日期是:' + convert(varchar(50), DateOfBirth, 103) as '学生信息'
from Students;
select StudentName + '的出生日期是:' + convert(varchar(50), DateOfBirth, 108) as '学生信息'
from Students;

DateOfBirth是DateTime类型,不转换会报错

------------------函数-----------------

计算日期差:datediff(日期格式,日期1, 日期2)

向下取整:Floor()

样例:

sql 复制代码
declare @days int, @BirthDay dateTime, @Age int
select @BirthDay = DateOfBirth from Students where StudentId = 100002
print '生日:' + convert(varchar(50), @BirthDay)
select @days = datediff(DAYOFYEAR,@BirthDay, getdate())
print '活了' + Convert(varchar(10), @days) + '天'
select @Age = FLOOR(@days / 365)
print '活了' + Convert(varchar(10), @Age) + '年'


结果:
    生日:02  7 1990 12:00AM
    活了12211天
    活了33年
相关推荐
zhoupenghui1686 分钟前
mysql 中如果条件where中有or,则要求or两边的字段都必须有索引,否则不能用到索引, 为什么?
数据库·mysql·索引
eggwyw1 小时前
完美解决phpstudy安装后mysql无法启动
数据库·mysql
LaughingZhu1 小时前
Product Hunt 每日热榜 | 2026-03-23
数据库·人工智能·经验分享·神经网络·chatgpt
2401_894241921 小时前
用Pygame开发你的第一个小游戏
jvm·数据库·python
java修仙传2 小时前
MySQL 事务隔离级别详解
数据库·mysql·oracle
Irissgwe2 小时前
MySQL存储过程和触发器专题
数据库·mysql·oracle
椎4952 小时前
Redis day02-应用-实战-黑马点评-短信登录
数据库·redis·spring
瀚高PG实验室2 小时前
易智瑞GeoScene Pro连接瀚高安全版数据库 458
数据库·安全·瀚高数据库
551只玄猫2 小时前
【数据库原理 实验报告3】索引的创建以及数据更新
数据库·sql·课程设计·实验报告·操作系统原理