SQL语句笔记

1.lect isnull(max(ID),1) as id from TB    查询最大ID,若为空范围1

2.set @date=convert(nvarchar(10),getdate(),112)    输出指定格式日期   nvarchar(10)表示日期长度,112表示格式参数

    常用格式参数  1): 05/16/06    20):  2006-05-16 10:57:47     21): 2006-05-16  10:57:47.157       25): 2006-05-16 10:57:47.250     101): 05/16/2006

111):  2006/05/16     112): 20060516      114): 10:57:49:547     120): 2006-05-16 10:57:49

3.模糊查询时,关键字中有%怎样转义:select * from tb where content like '%/%%' 

4.select DATEPART(MONTH/DAY/YEAR……,SYSDATETIME())  返回当前日期的年活月或日等等

5.Select CODE,CNAME,'标注列' as '标注' from wm.DRUGDICT   添加标注列

6.sql中使用as来重新命名列名

7.使用distinct过滤重复行   如:Select distinct * from tb

8.删除重复行: delete from tb where id>(select  min(ID) from tb t where tb.name=t.name)

 9.<>不等于   例:Select * from tb where id<>1 查询id不等于1的列          <>(iso标准)   !=(非iso标准)

10.内连接  inner join ……on(为条件)    例:Select tb1.a ,tb2.a from tb1 inner join tb2 on tb1.a=tb2.a

11.where tb like '_name'   表示查询以name结尾并且为5个字符数据

     where tb like '[C-P]'name   查询以C-P字符开头并且以Name结尾的的五个字符的数据

     where  tb like 'c[^ly]'   查询一c开始,其后两个字符不为ly的数据

12.order by 空值视为最低可能值

13.当Select ……与into  一起使用时,order by 不能保证按指定顺序插入数据

14.select ID,Name from tb where Name like '白%' grpup by rollup/cube(使用rollup可能影响结果集行数,使用cube不影响)(ID,Name) having ID>1000

15.after触发器,在执行insert,Update,Delete之后,for通after一样,,也可写成for after

     instead of ,执行触发器而不执行触发触发器的语句,从而代替触发语句

16.使用游标显示每一行数据

View Code
 1 declare @ID nvarchar(10)
 2 declare @Cname nvarchar(30)
 3 declare cursor1 cursor for select ID,Cname from WM.drugdict where Cname like '阿%'
 4 open cursor1
 5 fetch next from cursor1 into @ID,@Cname
 6 while(@@fetch_status=0)
 7 begin
 8 print 'ID:'+@ID
 9 print 'Cname'+@Cname
10 fetch next from cursor1 into @ID,@Cname
11 end 
12 close cursor1
13 deallocate cursor1

17.使用[truncate table]  tablename能快速删除表中记录,且无日志记录

18.创建事务

View Code
 1 USE [cesi]
 2 GO
 3 /****** Object:  StoredProcedure [dbo].[Myproc]    Script Date: 03/19/2013 10:14:10 ******/
 4 SET ANSI_NULLS ON
 5 GO
 6 SET QUOTED_IDENTIFIER ON
 7 GO
 8 ALTER proc [dbo].[Myproc]
 9 as
10  begin 
11    begin try  --开始捕获异常
12      begin transaction  --开始一个事务
13      delete from tb4
14      delete from tb3  --多条sql语句
15   commit transaction --提交事务
16   end try
17   begin catch
18    rollback transaction --事务回滚
19    end catch
20  end

 

   

      

 

 

posted @ 2013-03-17 11:14  随也缘也  阅读(123)  评论(0)    收藏  举报