存储过程的使用——表、临时表、表变量

--创建临时表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
posted @ 2017-06-24 14:58  乌柒柒  阅读(583)  评论(0编辑  收藏  举报