項目中常用的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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM