有趣的sql

1.操作字段

a. 添加字段

alter table CompanyRegisterOrder
add CreateTime datetime not null default getdate(), 
UpdateTime datetime not null default getdate(),
StateFlag int not null default 1

b.修改字段

--修改(手动修改表结构时,有时会遇到TimeOut过期的问题,用sql改的时候没有发现异常)
alter table Info
alter column ExpireDate datetime not null

c. 删除字段

alter table AgentOrder 
drop column SubjectId

d. 给列添加默认值

alter table CompanyRegisterToMajor
add constraint df default(getdate()) for UpdateTime

e. 删除约束

alter table CompanyRegisterOrder
drop constraint DF_CompanyRegisterOrder_MajorId

2.update ··· from ··· 根据两表关联ID更新对应数据

update tableA set tableA.aId= tableB.bId from tableB where tableA.aId=tableB.aId

3.select ··· into ··· 把A库里的表TableA及数据复制到B库中

   说明:要求目标TableA不存在,复制是会自动创建表名

select * into TableA from A..TableA

4.insert into ··· select ···把【BatchPhone】数据复制到【User】表中

   说明:要求目标User表存在

insert into 
[User]([Pwd],[Phone],[Email],[Contact]) select
'123456',Phone,'',[Contact]
from BatchPhone

5.使用case when实现批量更新单个字段

update Temp
    set EnPhone = case ID
        when 1 then '5E22374F6B846B8D58FE82EF3F0D74B1'
        when 2 then '5E22374F6B846B8D58FE82EF3F0D74B2'
        when 3 then 'D699ADE1E7897FEE727A37C7126333D3'
    end
  where ID in (1,2,3)

6.为某个字段追加值

 说明:当这个字段类型是整型时,其值会累加

update UserBasic set Contact+='追加的内容' where Id=1

7.inner join的另一种写法

select * from UserBasic a,
(select * from Company) b
where a.Id=b.UserId

8.判断结果是null返回0

select isnull(null,0)

行转列: https://www.cnblogs.com/no27/p/6398130.html

原文地址:https://www.cnblogs.com/paulhe/p/3702020.html