sqlserver 个人整理

1.创建临时表(临时表的生命周期是当前回话中)

//创建临时表是使用#+表名
//判断临时表是否存在
if object_id('tempdb..#ttt1') is not null 
Begin
    drop table #ttt1//删除临时表
End
select * into #ttt1 from mytable

2.update变异写法以及sqlserver中游标使用

//创建游标
declare mycursor cursor for 
select distinct a.ID from mytable1 a
inner join mytable2  b on a.ID=b.AID
where ...
//打开游标
open mycursor 
//定义参数用来读取游标
declare @code int
//游标移位
fetch next from mycursor into @code
while @@FETCH_STATUS=0//直到游标结束
begin
    declare @days int 
        //取时间差
    select @days=DATEDIFF(DAY,isnull(a.Date1,a.Date2),isnull(a.Date3,a.Date4))+1 from mytable1 a where a.CinemaFailID=@code
    print @code//打印
    print @days
    update c set c.column1=@days*10 from mytable1 c where ID=@code    
    update c set c.column1=(select SUM(column1) from mytable2 where AID=@code) from mytable1  c where ID=@code
    fetch next from mycursor into @code//游标移位    
end    
close mycursor//关闭游标
deallocate mycursor//销毁游标

3.sqlserver中判断表是否存在

IF EXISTS (SELECT 1 FROM sysobjects WHERE id =OBJECT_ID('mytable')
         AND type='U')
        DROP TABLE  mytable    

 4.sqlserver修改主键字段类型

--删除主键约束
alter table tablename drop constraint primiarykeyconstraintname
--修改主键类型
alter table tablename alter column primiarykeycolumnname bigint
--创建已有表主键约束
alter table tablename add constraint primiarykeyconstraintname primary key (primiarykeycolumnname)
原文地址:https://www.cnblogs.com/lcawen/p/6674590.html