管理

sql 常用语句积累

Posted on 2009-08-30 17:04  lzhdim  阅读(545)  评论(0编辑  收藏  举报
1.如何删除表中的重复记录?(这里指记录的每个字段都要相同)
select  distinct  *  into  #temp  from  tab  
delete  tab  
insert  tab  select  *  from  #temp  
drop  table  #temp
  
2.怎样返回数据库中用户表的表单名
select  name  from  sysobjects  where  xtype='U'  
select  name  from  sysobjects  where  xtype  =  'u'  and  status  >=0
  
3.返回两个表中共有的所有记录
select * from testTable as a inner join TestTableChild as b on a.id = b.parentid
  
4.返回两个表里共有的记录,且不重复select a.id,a.name,b.name from testTable as a inner join TestTableChild as b on a.id = b.parentid group by a.id,a.name,b.name  
5.向一个表A中插入记录,并且插入的记录在A中不存在(通过一个字段来判断)insert into trace_users (tracekey,muteSMS,CreateTime,traceuser,tracetime,traceSlot,traceduration)  Select 'TRACE_TIMER',0,getdate(),mobileid,getdate(),'30','0' from Epm_EmployeeList where corpid = 10001 and not exists (select traceuser from trace_users ) and mobileid like '13%' and len(mobileid) = 11  
6、根据出生日期,算出年龄DATEDIFF(month, T.Birthday, GETDATE()) AS MONTHS //得到月份
MONTHS /12
取整就是年龄 
7、等待时间再执行语句
waitfor delay '00:00:05'
select * from studentinfo
waitfor time ’23:08:00
select * from employee
 
8、指定值的范围查询stockname like '[a-zA-Z]%' --------- ([]指定值的范围)
 
stockname like '[^F-M]%' --------- (^
排除指定范围)  
9、从表中获取值并插入另一张表中insert into table2 (a) select a from table1  
10、备份与恢复数据库backup database SCardDB to disk = 'F:\SCardDB.20061010(105748).bak'restore   database   kangda   from   disk='d:\backup.bak‘  
11对查询结果随机排序
SELECT * FROM Northwind..Orders ORDER BY NEWID()
  
12、按姓氏笔画排序
Select * From TableName Order By CustomerName Collate Chinese_PRC_Stroke_ci_as
  
13获取某一个表的所有字段
select name from syscolumns where id=object_id('
表名')  
14、记录转换select *,case Type when 1 then '移动' when 2 then '联通' when 3 then '小灵通' end as TypeName from abc  
15、按拼音首字母排序select * from 表名 order by 列名 Collate Chinese_PRC_CS_AS_KS_WS
Copyright © 2000-2022 Lzhdim Technology Software All Rights Reserved