`

SQL语句 操作集合

阅读更多
 //保留小数位数

select cast(列名as 数值类型,如decimal,numeric等 (长度,小数点后位数)) 列名 from 表名

例:select cast(Sid as decimal(18,2)) Sid from User

//case 用法

单条件:select case xxxxx when null then '0' else '1' end from xxxx

多条件:  select case xxxx when '' then '0' when null then '0' else xxxx end from xxxx

 

//convert 用法
CONVERT(data_type(length),data_to_be_converted,style)
如:CONVERT(VARCHAR(19), 列名)
或:CONVERT(VARCHAR(19),GETDATE()) //获取日期后转为字串
或: CONVERT(VARCHAR(19), select count(*) from aaa) //将一个查询结果如count 转为字串

 

//SQL子查询及字串拼接

select f.*,
 (convert(varchar(30), (select count(*) from Report s where s.ReportCode=f.ReportCode and s.IsDefineReport='0' and s.IsFinish='1' )) || '/' ||
 convert(varchar(30), (select count(*) from Report s where s.ReportCode=f.ReportCode and s.IsDefineReport='0' ))) FinishStatus,
 from Report f
//本例子是查询一个表 这个表中包括定义表和子厂的表 总厂定义表和子厂表id相同 完成状态不同 本例子是在这个表中查询完成度 就是两个count拼接为类似 3/5

 

结果图:

 

//MS SQL 随机抽取
select top 2 * from xxx order by newid() 

 

SQL语句添加列:

alter table 表名 add 列名 类型 默认值 是否为空...

 

SQL语句删除列:

alter table 表名 drop 列名

 

SQL语句向表一插入表二的数据:

insert into tttt1 (col1, col2, col3, col4, Id) select * from tttt2
--后面可加where条件,列的个数及名称需统一

 

SQL语句将表二的数据更新为表一的数据:

update tttt1 set tttt1.Id=isnull(b.Id,'') from tttt2 b where tttt1.Id=b.Id and tttt1.code=b.code
--表一和表二的列名可不一致,表一不能加别名
 

 

 

 

 

 

 

  • 大小: 13.8 KB
0
3
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics