1. 取10--20条记录
select news_id from Item_T_Info_News where news_id>=(select max(t1.News_ID) from (select top 10 * from Item_T_Info_News order by News_ID) as t1) and news_id<=(select max(t2.News_ID) from (select top 20 * from Item_T_Info_News order by News_ID) as t2)
2. 表变量和临时表的定义
表变量
DECLARE @indextable table ( uid int identity(1,1), id int )
临时表
CREATE Table #temptable ( id int, date datetime )
当数据量大时,建议使用临时表!
3. 错开排序
declare @t table(empid int,empname varchar(10),deptid int) insert into @t select 1,'员工A',5 insert into @t select 2,'员工B',5 insert into @t select 3,'员工C',7 insert into @t select 4,'员工D',7 insert into @t select 5,'员工E',9 insert into @t select 6,'员工F',5 insert into @t select 7,'员工G',7 insert into @t select 8,'员工H',9 insert into @t select 9,'员工I',3 select px=(select count(1) from @t where deptid=a.deptid and empid<=a.empid),* from @t a order by px,deptid
4. 统计某一产品出现的次数
declare @myTable table ( pro_ID int, pro_count int ) insert into @myTable(pro_ID,pro_count) select OrderPro_ProID,count(OrderPro_ProID) from Item_T_Order_OrderPro group by OrderPro_ProID select * from @myTable
5. 按in的顺序排序
select * from Item_T_Pro_Product where Pro_ID in(90,153,158,80,76,98,96,85,101,104) ORDER BY charindex(','+cast(Pro_ID as varchar(10))+',', ',90,153,158,80,76,98,96,85,101,104,')
6. split函数
set ANSI_NULLS ON set QUOTED_IDENTIFIER ON go ALTER FUNCTION [dbo].[split] (@str nvarchar(4000),@code varchar(10),@no int ) RETURNS varchar(200) AS BEGIN declare @intLen int declare @count int declare @indexb int declare @indexe int set @intLen=len(@code) set @count=0 set @indexb=1 if @no=0 if charindex(@code,@str,@indexb)<>0 return left(@str,charindex(@code,@str,@indexb)-1) else return @str while charindex(@code,@str,@indexb)<>0 begin set @count=@count+1 if @count=@no break set @indexb=@intLen+charindex(@code,@str,@indexb) end if @count=@no begin set @indexe=@intLen+charindex(@code,@str,@indexb) if charindex(@code,@str,@indexe)<>0 return substring(@str,charindex(@code,@str,@indexb)+len(@code),charindex(@code,@str,@indexe)-charindex(@code,@str,@indexb)-len(@code)) else return right(@str,len(@str)-charindex(@code,@str,@indexb)-len(@code)+1) end return '' END