近老是遗忘很多sql函数.今天就花时间总结一下,也方便以后查找.也为各位同行们提供一个方便
最常用的就是日期函数
1 select getdate() as 'wawa_getdate' --当前时间 2 select getutcdate() as 'wawa_getutcdate' --获取utc时间 3 select day(getdate()) as 'wawa_day' --取出天 4 select month(getdate()) as 'wawa_month' --取出月 5 select year(getdate()) as 'wawa_year' --取出年 6 select dateadd(d,3,getdate()) as wawa_dateadd --加三天,注意'd'表示天,'m'表示月,'yy'表示年,下面一样 7 select datediff(d,'2004-07-01','2004-07-15') as wawa_datediff --计算两个时间的差 8 select datename(d,'2004-07-15') as wawa_datename --取出时间的某一部分 9 select datepart(d,getdate()) as wawa_datepart --取出时间的某一部分,和上面的那个差不多
还有就是数据库基本函数
View Code
再有就是数据库操作字符串函数
1 --字符串函数 2 select ascii(123) as '123',ascii('123') as '"123"',ascii('abc') as '"abc"' --转换成ascii码 3 select char(123),char(321),char(-123) --根据ascii转换成字符 4 select lower('ABC'),lower('Abc'),upper('Abc'),upper('abc') --转换大小写 5 select str(123.45,6,1), str(123.45,2,2) --把数值转换成字符串 6 select ltrim(' "左边没有空格"') --去空格 7 select rtrim('"右边没有空格" ') --去空格 8 select ltrim(rtrim(' "左右都没有空格" ')) --去空格 9 select left('sql server',3),right('sql server',6) --取左或者取右 10 11 use pubs 12 select au_lname,substring(au_fname,1,1) --取子串 13 from authors 14 order by au_lname 15 16 select charindex('123','abc123def',2) --返回字符串中指定表达式的起始位置 17 select patindex('123','abc123def'),patindex('%123%','abc123def') --返回表达式中某模式第一次出现的起始位置 18 select quotename('abc','{'),quotename('abc') --返回由指定字符扩住的字符串 19 select reverse('abc'),reverse('上海') --颠倒字符串顺序 20 select replace('abcdefghicde','cde','xxxx') --返回呗替换了指定子串的字符串 21 select space(5),space(-2)
补充一个 update [table] set [column]=REPLACE(column,'oldstr','newstr') sql替换某列字符串语句
数据库备份
- 备份:
- backup database BackupTest to disk='D:\db01.BAK' with NOINIT
- 恢复:
- restore database Backup01 from disk='D:\db01.BAK' with file=1,replace,RECOVERY
- 修改表的字段:
- alter table 表名 add 字段 类型
- 如:alter table B_Suggestion add Sip nvarchar(50)