• 15.6.8-sql小技巧


    取月头月尾:

    declare @someDay datetime,@firstDay datetime,@endDay datetime
    set @someDay='2015.2.2'
    set @firstDay=dateadd(month,datediff(month,0,@someDay),0)
    set @endDay=dateadd(month,datediff(month,-1,@someDay),-1)
    
    select @someDay,@firstDay,@endDay

     亮点在这里:

    declare @someDay datetime, @someDay2 datetime
    set @someDay =0
    set @someDay2=-1
    select @someDay,@someDay2 

    返回:

    不用游标,插入和升级数据:

    create table #AAA(id int, AAA int, BBB int,CCC int)
    create table #BBB(id int, CCC int)
    
    insert into #AAA select 1,1,1,1 union select 2,2,2,2 union select 3,3,3,3 union select 4,4,4,4
    insert into #BBB select 1,10 union select 2,6 union select 4,7-- union select 5,10 union select 8,100
    
    update #AAA set CCC=(select CCC from #BBB where #BBB.id=#AAA.id) where exists(select id from #BBB where id=#AAA.id)
    insert into #AAA select id,0,0,CCC from #BBB where not exists (select Id from #AAA where id=#BBB.id)
    select * from #AAA
    
    drop table #AAA
    drop table #BBB

    在#AAA的基础上升级#BBB的数据,有则改无则加

    在上面的基础上,继续升级:

    create table #AAA(id int,aaa int,bbb int,ccc int)
    create table #BBB(id int,ddd int,eee int)
    
    insert into #AAA select 1,1,1,1 union select 2,2,2,2 union select 3,3,3,3 union select 4,4,4,4
    insert into #BBB select 1,2,3 union select 2,3,4 union select 5,6,7
    
    update #AAA    
        set aaa=isnull((select top 1 ddd from #BBB where #BBB.id=#AAA.id),0),
            bbb=isnull((select top 1 eee from #BBB where #BBB.id=#AAA.id),0)
        --where exists (select id from #BBB where #BBB.id=#AAA.id)
    
    update #AAA    
        set aaa=isnull(b.ddd,0),
            bbb=isnull(b.eee,0)
        from #AAA a,#BBB b
        where a.id=b.id
    
    insert into #AAA
        select id,ddd,eee,0 from #BBB
        where not exists (select id from #AAA where #AAA.id=#BBB.id)
    
    
    select * from #AAA
    drop table #AAA
    drop table #BBB

    两个update#AAA的方法。第一个如果#BBB存在#AAA的id则修改对应值,不存在则将#AAA中的值归零。

    第二个如果#BBB存在则修改对应值,不存在则跳过。

  • 相关阅读:
    WIN7远程桌面连接--“发生身份验证错误。要求的函数不受支持”
    django-xadmin使用之更改菜单url
    django-xadmin使用之配置页眉页脚
    django-xadmin定制之列表页searchbar placeholder
    django-xadmin定制之分页显示数量
    Chrome无界面浏览模式与自定义插件加载问题
    Chrome开启无界面浏览模式Python+Windows环境
    django-xadmin中APScheduler的启动初始化
    处理nginx访问日志,筛选时间大于1秒的请求
    将Excel文件转为csv文件的python脚本
  • 原文地址:https://www.cnblogs.com/icyJ/p/4561001.html
Copyright © 2020-2023  润新知