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年
相关推荐
DO_Community1 分钟前
基于AI Agent模板:快速生成 SQL 测试数据
人工智能·python·sql·ai·llm·ai编程
爬山算法1 小时前
Redis(127)Redis的内部数据结构是什么?
数据结构·数据库·redis
应用市场1 小时前
Qt QTreeView深度解析:从原理到实战应用
开发语言·数据库·qt
q***96581 小时前
Spring Data JDBC 详解
java·数据库·spring
Hello,C++!2 小时前
linux下libcurl的https简单例子
linux·数据库·https
合方圆~小文2 小时前
高性能20倍变焦球机转动功能监控设备
数据结构·数据库·数码相机·模块测试
q***58193 小时前
【SQL】MySQL中的字符串处理函数:concat 函数拼接字符串,COALESCE函数处理NULL字符串
数据库·sql·mysql
懒羊羊不懒@3 小时前
【MySQL | 基础】多表查询
数据库·sql·mysql
百***6973 小时前
redis 使用
数据库·redis·缓存
mit6.8243 小时前
[Column] 构建十亿/s级DB | 索引DB&RTDB | Kafka 为中心 | Rust 构建引擎
数据库