一、定义变量
--简单赋值
declare @a int
set @a=5
print @a
--使用select语句赋值
declare @user1 nvarchar(50)
select @user1='张三'
print @user1
declare @user2 nvarchar(50)
select @user2 = Name from ST_User where ID=1
print @user2
--使用update语句赋值
declare @user3 nvarchar(50)
update ST_User set @user3 = Name where ID=1
print @user3
二、表、临时表、表变量
--创建临时表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
SQLSERVER存储过程基本语法(一)
最新推荐文章于 2024-09-22 16:22:27 发布