Chapter 4 函数
4.1 函数用法
4.2 函数的类型
4.2.1 标量函数
1.系统函数
1.1 条件表达式:case
select @intsDays =
case @chvScheduleFrequency
when 'monthly' then 30
when 'semi-monthly' then 15
when 'bi-weekly' then 14
when 'quarterly' then 92
end
语法:
case input _expression
when when_expression then result_expression
[......n]
[
else else_result_expression;
]
end
1.2 获取数据的相关信息
IsDate():确定一个表达式是否是有效日期,从文本文件中读取数据时,这个函数特别有用。
@chvLeaseDate varchar(50);
if IsDate(@chvLeaseDate) = 0
begin
Raiserror ('Unable to Convert to date.', 16, 1);
return -1;
end
IsNumber():用来判断是否可以将字符值或表达式转换为任一数值类型(int、smallint、tinyint、real、float、money、smallmoney、decimal、numeric)
DataLength():返回一个表达式的字节数。而不是像Len()函数那样返回字符数。任何一种Unicode数据类型的每个字符使用两个字节
Binary_CheckSum():用来计算一个指定表达式或列集合的二进制检验和checksum。这个函数被设计用来探测记录中的修改。
1.3 处理空值的函数
NullIf(expression, expression):如果两个表达式相等,返回空值。如果两个表达式不相等,函数返回第一个表达式的值。
IsNull(check_expression, replacement_value):检查参数check_expression的值,如果为空,则返回replacement_value;如果check_expression不为空,则函数返回check_expression。
这个函数不是用来测试一个表达式的值是否为空。取而代之的是:if expression is null | if expression is not null.
Coalesce(expression [,......n]):通常用来联合几个列的值,第一个非空表达式就是该函数的结果。
1.4 转换函数
cast()和convert()函数用来显式的将数据从一个数据类型转换为另一个指定的数据类型。两者区别:Convert()允许指定结果的格式。
cast(expression as data_type);
convert(data_type[(length)], expression, [, style]);
style是指将日期和时间或者数值表达式转换成字符串时所用的格式。
select GetData() standard, Convert(varchar, GetData(), 104) German;
select "Error [" +cast(@@Error as varchar) + "] has occurred.";
1.5 关于当前会话的信息
App_Name()
Host_Id()
Host_Name()
Permissions()
Current_User
Session_User
System_User
User_Name()
1.6 日期和时间函数
Get(Current)Date:返回datetime格式的系统时间。
GetUtcDate():返回格林威治时区的日期和时间,也称为世界调整时间(Universal Time Coordinate,UTC)
提取日期或时间值
DAY(datetime),MONTH(datetime),YEAR(datetime):返回整型值。
DatePart(datepart, date),DateName(datepart,date)
DateAdd(datepart, number, date):在date值中添加以datepart间隔的number。
DateDiff(datepart, startdate, enddate):返回startdate和enddate之间的datepart间隔值。
datepart表见书P108
1.7 基本字符串操作
Len(string_expression):返回字符串的长度(字符个数)。DataLength()将返回参数值的字节数。
Left(Character_expression, interger_expression)
Right(Character_expression, interger_expression)
substring(expressioin, start, length)
CharIndex(expression1, expression2, [start_location]):返回一个字符串expression1在另一个字符串expression2中第一次出现的位置。
PatIndex('%pattern%', expression)
1.8 字符串转换
LTrim(character_expression)
RTrim(character_expression)