SqlServer表、临时表、表变量和常用逻辑处理操作

---------------表、临时表、表变量-----------------
--创建临时表1
create  table  #DU_User1
(
      [ID] [ int ]   NOT  NULL ,
      [Oid] [ int ]  NOT  NULL ,
      [Login] [nvarchar](50)  NOT  NULL ,
      [Rtx] [nvarchar](4)  NOT  NULL ,
      [ Name ] [nvarchar](5)  NOT  NULL ,
      [ Password ] [nvarchar]( max )  NULL ,
      [State] [nvarchar](8)  NOT  NULL
);
--向临时表1插入一条记录
insert  into  #DU_User1 (ID,Oid,[Login],Rtx, Name ,[ Password ],State)  values  (100,2, 'LS' , '0000' , '临时' , '321' , '特殊' );
 
--从ST_User查询数据,填充至新生成的临时表
select  *  into  #DU_User2  from  ST_User  where  ID<8
 
--查询并联合两临时表
select  *  from  #DU_User2  where  ID<3  union  select  *  from  #DU_User1
 
--删除两临时表
drop  table  #DU_User1
drop  table  #DU_User2

--创建临时表
CREATE  TABLE  #t
(
     [ID] [ int ]  NOT  NULL ,
     [Oid] [ int ]  NOT  NULL ,
     [Login] [nvarchar](50)  NOT  NULL ,
     [Rtx] [nvarchar](4)  NOT  NULL ,
     [ Name ] [nvarchar](5)  NOT  NULL ,
     [ Password ] [nvarchar]( max )  NULL ,
     [State] [nvarchar](8)  NOT  NULL ,
)
 
--将查询结果集(多条数据)插入临时表
insert  into  #t  select  *  from  ST_User
--不能这样插入
--select * into #t from dbo.ST_User
 
--添加一列,为int型自增长子段
alter  table  #t  add  [myid]  int  NOT  NULL  IDENTITY(1,1)
--添加一列,默认填充全球唯一标识
alter  table  #t  add  [myid1] uniqueidentifier  NOT  NULL  default (newid())
 
select  *  from  #t
drop  table  #t
--给查询结果集增加自增长列
 
--无主键时:
select  IDENTITY( int ,1,1) as  ID,  Name ,[Login],[ Password ]  into  #t  from  ST_User
select  *  from  #t
 
--有主键时:
select  ( select  SUM (1)  from  ST_User  where  ID<= a.ID)  as  myID,*  from  ST_User a  order  by myID
--定义表变量
declare  @t  table
(
     id  int  not  null ,
     msg nvarchar(50)  null
)
insert  into  @t  values (1, '1' )
insert  into  @t  values (2, '2' )
select  *  from  @t
----------逻辑处理操作-----------
---while:while计算1到100的和
declare  @a  int
declare  @ sum  int
set  @a=1
set  @ sum =0
while @a<=100
begin
     set  @ sum +=@a
     set  @a+=1
end
print @ sum


--条件语句-----
--if,else条件分支
if(1+1=2)
  begin
     print  '对'
  end
else
begin
     print  '错'
end
 
--when then条件分支
declare  @today  int
declare  @week nvarchar(3)
set  @today=3
set  @week= case
     when  @today=1  then  '星期一'
     when  @today=2  then  '星期二'
     when  @today=3  then  '星期三'
     when  @today=4  then  '星期四'
     when  @today=5  then  '星期五'
     when  @today=6  then  '星期六'
     when  @today=7  then  '星期日'
     else  '值错误'
end
print @week

猜你喜欢

转载自boonya.iteye.com/blog/1808186