1、高效分页
select * from
(select *,row_number() over(order by id desc) rownum from table)tem
where tem.rownum>(@pageCurrent-1)*@pageSize and rownum<=@pageCurrent*@pageSize
2、递归查询
with cpt as
(
select id from table where id=1
union all
select c.id from table c inner join cpt on c.pid=cpt.id
)
select * from cpt
3、系统操作
select name from sysobjects where xtype='TR' --所有触发器
select name from sysobjects where xtype='P' --所有存储过程
select name from sysobjects where xtype='V' --所有视图
select name from sysobjects where xtype='U' --所有表
4、去除一对多重复项
select max(ColorID) From base_Color_View where ProductID IN(12,13) Group by ProductID
5、时间间隔
DateDiff(s,InputTime,getdate())>2*24*60*60 --大于两天
6、除非另外还指定了 TOP 或 FOR XML,否则,ORDER BY 子句在视图、内联函数、派生表、子查询和公用表表达式中无效
select * from
(
select top 100 percent * from tab where ID>20 order by userID desc --tab 是视图
) as a order by date desc
7、update 多表更新
update a set a.discout=b.discount from a,b where a.id=b.id
8、获取七天前的此时此刻
select getdate()-7
9、left、right join的时候,会把left的数据全部拿出来,内部条件无效
SELECT b.ImageID, g.ImageGroupID FROM base_ImageGroup AS g LEFT OUTER JOIN base_Image AS b
ON g.ImageGroupID = b.ImageGroupID and g.del=0 AND b.Del = 0 --这里面g.del=0是无效的
9、创建表变量
declare @tb table
(
id int
)
insert into @tb select id from tb
10、把数据连接成字符串
--stuff()、for xml path
select stuff((select ','+col from tb for xml path('')),1,1,'')--1,2,3,4
11、判断是否当天的数据
DateDiff(dd,'数据时间',getdate())=0
12、执行存储过程传参只能是已赋值的变量
EXEC '存储过程' GETDATE(),GETDATE()--错误
DECLARE @NowTime DATETIME
SET @NowTime=GETDATE()
EXEC '存储过程' @NowTime,@NowTime--正确