• 开发中经典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

  • 相关阅读:
    Jsoup的使用总结
    pip install r 是什么意思
    【python3基础】相对路径,‘/’,‘./’,‘../’
    nmon安装使用及结果分析(转)
    Python raise用法(超级详细,看了无师自通)(转)
    nmon和nmon_analyser的安装(转)
    扩展:对数组进行封装,实现增删改查功能
    简单实现链表LinkedList
    ArrayList与LinkedList的区别
    使用PowerDesigner对数据库建模
  • 原文地址:https://www.cnblogs.com/l1pe1/p/8931709.html
Copyright © 2020-2023  润新知