天天看點

開發中經典sql總結

 1、說明:顯示文章、送出人和最後回複時間

  select a.title,a.username,b.adddate ,(select max(adddate) from table where table.title=a.title) adddate from table a

  2、說明:兩張關聯表,删除主表中已經在副表中沒有的資訊

  delete from table1 where not exists ( select * from table2 where table1.field1=table2.field1 )

3、說明:日程安排提前五分鐘提醒

  SQL: select * from 日程安排 where datediff('minute',f開始時間,getdate())>5

  4、說明:一條sql 語句搞定資料庫分頁

  select top 10 b.* from (select top 20 主鍵字段,排序字段 from 表名 order by 排序字段 desc) a,表名 b where b.主鍵字段 = a.主鍵字段 order by a.排序字段

 5、說明:選擇在每一組b值相同的資料中對應的a最大的記錄的所有資訊(類似這樣的用法可以用于論壇每月排行榜,每月熱銷産品分析,按科目成績排名,等等.)

  select a,b,c from tablename ta where a=(select max(a) from tablename tb where tb.b=ta.b)

 6、說明:包括所有在 TableA 中但不在 TableB和TableC 中的行并消除所有重複行而派生出一個結果表

  (select a from tableA ) except (select a from tableB) except (select a from tableC)

   7、說明:随機取出10條資料

  select top 10 * from tablename order by newid()

    8、說明:删除重複記錄

   delete from tablename where id not in (select max(id) from tablename group by col1,col2,...)

  10、說明:列出資料庫裡所有的表名

  select name from sysobjects where type='U' // U代表使用者

 11、說明:列出表裡的所有的列名

  select name from syscolumns where id=object_id('TableName')

 12、說明:列示type、vender、pcs字段,以type字段排列,case可以友善地實作多重選擇,類似select 中的case。

  select type,sum(case vender when 'A' then pcs else 0 end),sum(case vender when 'C' then pcs else 0 end),sum(case vender when 'B' then pcs else 0 end) FROM tablename group by type

 13、說明:選擇從10到15的記錄

  select top 5 * from (select top 15 * from table order by id asc) table_别名 order by id desc

  14、SQL SERVER中直接循環寫入資料

  declare @i int

  set @i=1

  while @i<30

  begin

   insert into test (userid) values(@i)

   set @i=@i+1

  end

15 sp_executesql 用法

Declare @SQL nvarchar(max);
Declare @DonatorId int = 2;
Declare @DonatorName varchar(10);
set @SQL = 'SELECT * FROM dbo.Donators WHERE DonatorId = @id';
EXEC sp_executesql
    @stmt = @SQL,
    @params = N'@id as int',
    @id = @DonatorId;

16.select DATENAME(DW,getdate()) as  今天周幾

17.查詢期刊的檔期期期号和下一期期号
SELECT TOP 100 A.[Id]
      ,A.[Issue]     
      ,(SELECT MIN(ISSUE) FROM [Issue] B WHERE B.Issue>A.Issue ) NextIssue
  FROM [Issue] A

18.sqlserver 存儲過程事務異常處理

CREATE PROCEDURE YourProcedure      
AS  
BEGIN  
    SET NOCOUNT ON;  
  
    BEGIN TRY---------------------開始捕捉異常  
       BEIN TRAN------------------開始事務  
        UPDATE A SET A.names = B.names FROM 表1 AS A INNER JOIN 表2 AS B ON A.id = B.id  
  
        UPDATE A SET A.names = B.names FROM 表1 AS A INNER JOIN 表2 AS B ON A.TEST = B.TEST  
  
    COMMIT TRAN -------送出事務  
    END TRY-----------結束捕捉異常  
    BEGIN CATCH------------有異常被捕獲 
       SELECT ERROR_NUMBER() AS ErrorNumber,  
            ERROR_SEVERITY() AS ErrorSeverity,  
            ERROR_STATE() as ErrorState,  
            ERROR_PROCEDURE() as ErrorProcedure,  
            ERROR_LINE() as ErrorLine,  
            ERROR_MESSAGE() as ErrorMessage;  
        IF @@TRANCOUNT > 0---------------判斷有沒有事務  
        BEGIN  
            ROLLBACK TRAN----------復原事務  
        END   
        EXEC YourLogErrorProcedure-----------記錄存儲過程執行時的錯誤資訊,自定義  
    END CATCH--------結束異常處理  
END  

19.行列轉換
SELECT [Id]
      ,[StudentName]
      ,[KeCheng]
      ,[ChengJi]
  FROM [Mytest].[dbo].[ChengJi] 
  
  select [StudentName],
  max(case(kecheng) when '數學' then chengji end) as '數學',
  max(case(kecheng) when '國文' then chengji end) as '國文',
  max(case(kecheng) when '英語' then chengji end) as '英語'  
  from [Mytest].[dbo].[ChengJi] group by [StudentName]
      
 20 計算中null值得處理
      

SELECT COALESCE('',0)    結果0

SELECT COALESCE('    ',0)   結果0

SELECT COALESCE(null,0)    結果0

SELECT COALESCE(123,0)       結果123

SELECT ISNULL('',0)       結果''

SELECT ISNULL(null,0)     結果0

SELECT ISNULL(123,0)    結果123

由結果結果可以看出COALESCE函數對于空值處理和NULL值都起作用。

 21 批量更新資料
      
update S_USER set account=p.account from S_PERSON p where p.id=S_USER.person_id;
  update [ylb_play_type]  set PlayOdds= v2.PlayOdds from (select * from [ylb_play_type] where LotteryId=13) v2where [ylb_play_type].LotteryId=14  and v2.PlayName=[ylb_play_type].PlayName