有用的SQL语句,更新中~

动态分页:
这语句很有用,我在我写的类中一直用到,可能查出数据库中一段数据出来,当然可以加条件的,这样的话可以减轻服务器的负担。
1、select top 5 * from users
表示查出users表中前5条记录,如果是想查20-30这段记录呢:
2、select top 10 * from users where id not in (select top 20 * from users )
加上条件和排序
3、select top 10 * from users where id not in (select top 20 * from users where name='张三'   order by Id desc) and name='张三'  order by Id desc
不过在ACCESS中这个TOP会和SQL有一点点不同,就是说当top 0的时候会出错,这里要注意一下。
如果分页后,再对这几条记录排序呢?这里有两种办法:
一、用临时表:
select top 5 * into #B from Users select * from #B order by name desc drop table #B
删除临时表:
if  object_id('tempdb..#B') is not null
begin
   drop table #B
end

加上条件:
select top 5 * into #Q from Users where Id not in(select top 2 Id from Users where Sex='0' ) and Sex='0' select * from #Q order by name desc drop table #Q
不过这里很明显是用了多条SQL了,
二、一句SQL:
select * from (select top 5 * from Users order by ID asc) as V order by Name Desc
当然也可以加条件了:
select * from ( select top 5 * from Users where Id not in(select top 2 Id from Users where Sex='0'  order by Id asc) and Sex='0' order by Id asc) as T order by Name asc
上一句是分页加条件排序,很有用~

 

这么多天都没来BLOG看看了,今天来更新点点内容,学习笔记:
SQL事务:
 create   table   #Table1   (a   tinyint)  
  go 

begin   tran
      insert   #table1   values(1)                             ----成功 
if @@error <> 0 rollback
  commit   tran   


  begin   tran
      insert   #table1   values(1)                             ----成功 
if @@error <> 0 rollback
      insert   #table1   values(1000)                       ----这句将报错  
if @@error <> 0 rollback
  commit   tran   


  go  
  select   *   from   #table1    
  go  
  drop   table   #table1


这里创建了临时表#Table1,在第一个事务中,增加了合法数据,显然@@error为0,所以正常地commit

在第二个事务中,第二条语句 insert   #table1   values(1000) 执行错误,rollback


select * from master..sysprocesses where blocked<>0

可查看当前堵塞的事务信息.

如果当前由于某些原因(如事务堵塞),SQL会加表锁,这时查询这个表不会有结果,有一个方式可以解决:

select title_id,
price
from titles WITH (NOLOCK)
 where title_id = 'BU2075'

加上WITH (NOLOCK)就可以了,不过它是堵塞那个事务之前的数据,有时候会产生赃数据,切记!!
很实用~小记一下。

posted @ 2008-04-03 13:16  point.deng  阅读(454)  评论(1编辑  收藏  举报