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年
相关推荐
前端精髓2 分钟前
三种方式实现 Agent 工具调用:OpenAI、LangChain 与 LangGraph
前端·数据库·langchain
Ryan-Zhong12 分钟前
视频解析 API 拒绝解析怎么判定:reason 分流与门禁
java·数据库·音视频
无级程序员1 小时前
dolphinscheduler3.x从mysql迁移到postgresql
数据库·mysql·postgresql
HEJOO92 小时前
MySQL 日期时间类型怎么选:DATE、DATETIME、TIMESTAMP、TIME、YEAR 全解析
android·数据库·mysql
lbb 小魔仙2 小时前
拆开时序数据库再看选型-时序数据库是什么+2026年主流产品选型指南和场景全解析
数据库·时序数据库
RestCloud2 小时前
ETLCloud告警配置实战:5种通知渠道+5个基线指标,一次配齐_
数据库·数据安全·etl·etlcloud·数据传输·数据集成平台·告警配置
IT古董3 小时前
《Agent开发工程师成长指南》- 第4章 第6节:Prompt模板设计——如何把零散的提示词变成可复用的工程资产?
运维·服务器·数据库
骑着蜗牛撵大象3273 小时前
从0实现C++ AI大模型接入SDK(十):DataManager业务实现——数据库CRUD、事务管理与数据一致性
数据库·c++·人工智能·sqlite·事务管理·数据一致性
阿正的梦工坊3 小时前
深入理解 B+ Tree:从二叉搜索树、B Tree 到数据库索引的底层原理
数据库
夜雪一千4 小时前
PostgreSQL 的触发器如何写
linux·数据库·postgresql