1.根据不同判断条件显示
select case sex when 'M' then '男' when 'F' then '女' else '未知' end as sexStr
--select case when sex = 'M' then '男' when sex = 'F' then '女' else '未知' end as sexStr
--跟上面一样效果,一个是case函数,一个是case搜索函数
2.根据条件显示原始字段
select case sex when 'M' then '男' else sex end as sexStr
3.判断为空
select * from table where Id is not null--不为空
select * from table where Id is null--为空
4.'''转义字符
select * from table where name = '''jorden';
--在单引号'前面再加一个单引号,意思是'jorden进行匹配
--%号和_号
select * from table where name like '[%]a'
select * from table where name = '[_]a'
--使用两个方括号对%和_进行转义
5.某个查询出来的值用逗号进行拼接
select stuff((select ','+name from table for xml path('')),1,1,'') as nameStr;
--所有的name值会拼接成一个nameStr值,用逗号分隔
--实例
select case when a IS NULL then '''''' else a end as CompStr from
(select stuff((select ','''+pe.CompNo+'''' from PlateRight pr
left join Plate pe on pr.PlateId=pe.PlateId
where pr.EmpNo = 'CH4757' for xml path('')),1,1,'')as a ) b
6.判断数据库,表是否存在(一般不存在可以新建数据库或者表)
--添加DimissionList表的sql
use FtnDorm
go
if Exists(SELECT * FROM sysobjects WHERE name='DimissionList')--其中DimissionList为表名
print('表已存在');
else
--新建表
begin
create table DimissionList(
DormDimissionListId INT NOT NULL IDENTITY(1,1),
CompName nvarchar(100) not null,
DeptName nvarchar(100) not null,
EmpNo nvarchar(50) not null,
EmpName nvarchar(50) not null,
OutDate smalldatetime not null,
IsCalculate int not null
)
print('新建DimissionList表成功')
end
go
判断数据库是否存在
--测试检验数据库是否存在
if EXISTS(SELECT * FROM sys.databases WHERE name='FtnDormNew')--其中FtnDormNew为数据库名
print('有FtnDormNew数据库')
else
print('无FtnDormNew数据库')
go
7.字段类型转化CONVERT()
int 转 varchar
convert(varchar,name);
varchar 转 int
convert(int,name);
8.判断字段为空时置值为0,否则为原值
select ISNULL(filed,0) as filed from table
9.设置字段精度
SELECT CAST('123.4' AS decimal(9,2))
9代表数值所能支持总位数,小数点左边和右边位数之和,2表示字段所能支持的小数点位数
这里显示值为:123.40
10.判断表里面是否存在要添加的字段
IF COL_LENGTH('Room', 'RoomCarNo') IS NOT NULL
PRINT N'RoomCarNo列已存在,添加失败'
ELSE
begin
alter table Room add RoomCarNo nvarchar(50) null
PRINT N'RoomCarNo列已成功添加'
end