ÍòÄܵķÖÒ³sql(ת)
CREATE proc page
@RecordCount int output,
@QueryStr nvarchar(100)='table1',--±íÃû¡¢ÊÓͼÃû¡¢²éѯÓï¾ä
@PageSize int=20, --ÿҳµÄ´óС(ÐÐÊý)
@PageCurrent int=2, --ÒªÏÔʾµÄÒ³ ´Ó0¿ªÊ¼
@FdShow nvarchar (1000)='*', --ÒªÏÔʾµÄ×Ö¶ÎÁбí
@IdentityStr nvarchar (100)='id', --Ö÷¼ü
@WhereStr nvarchar (200)='1=1',
@FdOrder nvarchar(100)='desc' --ÅÅÐò Ö»ÄÜÈ¡desc»òÕßasc
as
declare
@sql nvarchar(2000)
set @sql = ''
if @WhereStr = ''
set @WhereStr = '1=1'
if @PageCurrent = 0 begin
set @sql = 'select top ' + cast(@PageSize as nvarchar(3)) + ' ' + @FdShow + ' from ' + @QueryStr + ' where ' + @WhereStr + ' order by ' + @IdentityStr + ' ' + @FdOrder
end
else begin
if upper(@FdOrder) = 'DESC' begin
set @sql = 'select top ' + cast(@PageSize as nvarchar(3)) + ' ' + @FdShow + ' from ' + @QueryStr + ' where ' + @WhereStr + ' and ' + @IdentityStr + '< ( select min(' + @IdentityStr + ') from (select top ' + cast(@PageSize*@PageCurrent as nvarchar(10)) + ' ' + @IdentityStr + ' from ' + @QueryStr + ' where ' + @WhereStr + ' order by ' + @IdentityStr + ' desc) as t) order by ' + @IdentityStr + ' desc'
end
else begin
set @sql = 'select top ' + cast(@PageSize as nvarchar(3)) + ' ' + @FdShow + ' from ' + @QueryStr + ' where ' + @WhereStr + ' and ' + @IdentityStr + '> ( select max(' + @IdentityStr + ') from (select top ' + cast(@PageSize*@PageCurrent as nvarchar(10)) + ' ' + @IdentityStr + ' from ' + @QueryStr + ' where ' + @WhereStr + ' order by ' + @IdentityStr + ' asc) as t) order by ' + @IdentityStr + ' asc'
end
end
--print @sql
execute(@sql)
if(@RecordCount is null or @RecordCount<=0)begin
declare @tsql nvarchar(200)
set @tsql=N'select @RecordCount = count(*) from ' + @QueryStr + ' where ' + @WhereStr
exec sp_executesql @tsql,N'@RecordCount int output',@RecordCount output
select @Recordcount
end
GO
Ïà¹ØÎĵµ£º
countÓï¾äÖ§³Ö*¡¢ÁÐÃû¡¢³£Á¿¡¢±äÁ¿,²¢ÇÒ¿ÉÒÔÓÃdistinct¹Ø¼ü×ÖÐÞÊΣ¬ ²¢ÇÒcount(ÁÐÃû)²»»áÀÛ¼ÆnullµÄ¼Ç¼¡£ÏÂÃæËæ±ãÓÃһЩÀý×Óʾ·¶Ò»ÏÂcountµÄ¹æÔò£º±ÈÈç¶ÔÈçϱí×öͳ¼Æ£¬ËùÓÐÁÐÕâÀﶼÓÃsql_variantÀàÐÍÀ´±íʾ¡£
if (object_id ('t_test' )> 0 )
drop table t_test
go
create table t_test (a ......
±íÖÐÖ÷¼ü±ØÐëΪ±êʶÁУ¬[ID] int IDENTITY (1,1)
1.·ÖÒ³·½°¸Ò»£º(ÀûÓÃNot InºÍSELECT TOP·ÖÒ³)
Óï¾äÐÎʽ£º
SELECT TOP Ò³¼Ç¼ÊýÁ¿ *
from ±íÃû
WHERE (ID NOT IN
(SELECT TOP (ÿҳÐÐÊý*(Ò³Êý-1)) ID
from ±íÃû
ORDER BY ID))
ORDER BY ID
//×Ô¼º»¹¿ÉÒÔ¼ÓÉÏһЩ²éѯ ......
±íÖÐÖ÷¼ü±ØÐëΪ±êʶÁУ¬[ID] int IDENTITY (1,1)
1.·ÖÒ³·½°¸Ò»£º(ÀûÓÃNot InºÍSELECT TOP·ÖÒ³)
Óï¾äÐÎʽ£º
SELECT TOP Ò³¼Ç¼ÊýÁ¿ *
from ±íÃû
WHERE (ID NOT IN
(SELECT TOP (ÿҳÐÐÊý*(Ò³Êý-1)) ID
from ±íÃû
ORDER BY ID))
ORDER BY ID
//×Ô¼º»¹¿ÉÒÔ¼ÓÉÏһЩ²é ......
Ô¶³ÌÁ¬½Ósql server 2000·þÎñÆ÷µÄ½â¾ö·½°¸
----ת×Ô£º·ÉºüСÎÝ
ÓÉÓ ......