项目中常用的SQL语句(SQL SERVER2008R2专版)

1、exists 关键字的使用

/****** Script for SelectTopNRows command from SSMS  ******/
SELECT   [RoleId]
      ,[RoleOrderId]
      ,[RoleName]
      ,[RoleStatus]
      ,[RoleInsertTime]
      ,[RoleUpdateTime]
      ,[RoleRemark]
  FROM  [Math_RoleInfo]
   where exists
  ( SELECT * from Math_User_Role_Select 
  where [Math_RoleInfo].[RoleId]=Math_User_Role_Select.[RoleId])

2、case when 的两种情况

/****** Script for SelectTopNRows command from SSMS  ******/
SELECT   [RoleId]
      ,[RoleOrderId]
      ,[RoleName]
      ,[RoleStatus]
      ,[RoleInsertTime]
      ,[RoleUpdateTime]
      ,[RoleRemark]
    , case  RoleStatus
     when 2 then '不正常'
     else '默认值'  
     end as Name1
  FROM  [Math_RoleInfo]
  
/****** Script for SelectTopNRows command from SSMS  ******/
SELECT   [RoleId]
      ,[RoleOrderId]
      ,[RoleName]
      ,[RoleStatus]
      ,[RoleInsertTime]
      ,[RoleUpdateTime]
      ,[RoleRemark]
    , case  
     when RoleStatus=2 then '不正常'
     else '默认值'  
     end as Name1
  FROM  [Math_RoleInfo]
  

3、substring("abcdef",2,3) 得到 bcd

4、left("abcdefg",1) a

5、right("abcdefg",1)f

6、cast 和convert

select cast(1 as varchar(400)) as Name

select convert(varchar(10),getdate(),20)/*2018-02-27*/
select convert(varchar(10),getdate(),120) --2018-02-27
select convert(varchar(10),getdate(),102)--2018.02.27

 7、group by 

/****** Script for SelectTopNRows command from SSMS  ******/
SELECT   [RoleId],max(isnull(RoleStatus,100)) as maliang
      
  FROM  [Math_RoleInfo]
  group by [RoleId]
  order by maliang
 
  

 8、dateadd操作

select dateadd(year,1,getdate())
select dateadd(month,1,getdate())
select dateadd(day,1,getdate())
select dateadd(quarter,1,getdate())

9、year month day函数

select year(getdate())
select month(getdate())
select day(getdate())

10、datediff()

定义和用法

DATEDIFF() 函数返回两个日期之间的时间。

语法

DATEDIFF(datepart,startdate,enddate)

startdate 和 enddate 参数是合法的日期表达式。

datepart 参数可以是下列的值:

datepart缩写
yy, yyyy
季度 qq, q
mm, m
年中的日 dy, y
dd, d
wk, ww
星期 dw, w
小时 hh
分钟 mi, n
ss, s
毫秒 ms
微妙 mcs
纳秒 ns

实例

例子 1

使用如下 SELECT 语句:

SELECT DATEDIFF(day,'2008-12-29','2008-12-30') AS DiffDate

结果:

DiffDate
1

例子 2

使用如下 SELECT 语句:

SELECT DATEDIFF(day,'2008-12-30','2008-12-29') AS DiffDate

结果:

DiffDate
-1

分页操作。

select * from (
SELECT ROW_NUMBER() over(order by [DT_RowId])TT ,
 [DT_RowId]
      ,[name]
      ,[office]
      ,[address]
      ,[Idx]
      ,[Salary]
      ,[Score]
  FROM [Officer]) t
  where t.TT between 1 and 2

 新增数据加入自增长

insert intoTable (Name, Num)
values ('aa', 5);
go
select  @@IDENTITY AS 'Identity';
go
原文地址:https://www.cnblogs.com/sexintercourse/p/8481599.html