当前位置:Gxlcms > mysql > sqlserver简单示例

sqlserver简单示例

时间:2021-07-01 10:21:17 帮助过:56人阅读

示例 1、建立一个表,然后通过存储过程往该表中插入100条记录 create table teachers(id int primary key not null identity(10000,100),tea_name varchar(50),tea_age int default 20) create procedure insert1000teachers as declare @tea_name varchar(5

示例
1、建立一个表,然后通过存储过程往该表中插入100条记录
create table teachers(id int primary key not null identity(10000,100),tea_name varchar(50),tea_age int default 20)
create procedure insert1000teachers
as
declare @tea_name varchar(50)
declare @tea_age int
declare @index int
declare @count int
set @index=1
set @count=100
while @index<@count
begin
set @tea_age=30*rand()
set @tea_name='teacher'
set @tea_name=@tea_name+convert(varchar,@index)
insert into teachers(tea_name,tea_age)
values(@tea_name,@tea_age)
set @index=@index+1
end
2、创建数据库
create database test1
on
primary
(
name=t1_dat,
filename='d:/test_database/1/t1_dat.mdf',
size=1,
filegrowth=15%,
maxsize=50
),
(
name=t2_dat,
filename='d:/test_database/1/t2_dat.ndf',
size=1,
maxsize=UNLIMITED,
filegrowth=1
)
log on
(
name=t_log,
filename='d:/test_database/1/t_log.ldf',
size=1,
maxsize=UNLIMITED,
filegrowth=1
)
3、增加一个数据文件到指定的数据库
alter database test1
add
file
(
name=t3_dat,
filename='d:/test_database/1/t3_dat.ndf',
size=1,
maxsize=UNLIMITED,
filegrowth=1
)
4、增加组
alter database test1
add
filegroup filegroup1
5、增加一个数据文件到指定的组
alter database test1
add file
(
name=t4_dat,
filename='d:/test_database/1/t4_dat.ndf'
)
to filegroup filegroup1
6、对象重命名
更改字段名:sp_rename 'teachers.tea_name','tea_name1','column'
更改表名:sp_rename 'dbo.teachers','teachers1'
7、查看存储过程的内容:
sp_helptext insert1000teachers
8、采用存储过程实现:根据存储过程中的内容,查找存储过程的名字
create procedure getProcedureByBodyWords
@patpro varchar(100),--存储过程中的任意内容
@proname varchar(50) --存储过程的部分或者全名,或者为null
as
begin
select name from sysobjects where id in
(select id from syscomments where text like '%'+@patpro+'%')
and name like case when @proname is null then '%' else '%'+@proname+'%' end
end
如有存储过程名为insert1000teachers,操作如下可得其全名
exec getProcedureByBodyWords 'insert','insert1000'
9、采用触发器备份数据表中的数据:
建立测试数据表:
一个用于插入数据,test3
另一个作为备份,test3_bak
create table test3(id int primary key not null identity(1,1),uname varchar(20),uage int);
create table test3_bak(id int primary key not null identity(1,1),bid int,uname varchar(20),uage int,active char(1));

编写备份用的触发器,只有更新或者是插入的时候才触发
alter trigger test3_bak_insert_update
on test3
for insert,update
as
declare @id int
declare @uname varchar(20)
declare @uage int
begin
select @id=id,@uname=uname,@uage=uage from inserted
if @id<>0
begin
update test3_bak set active='0' where bid=@id
insert into test3_bak(bid,uname,uage,active)
values(@id,@uname,@uage,'1')
end
end
测试数据:
insert into test3(uname,uage) values('FLB',20)
insert into test3(uname,uage) values('FLB1',21)
insert into test3(uname,uage) values('FLB2',22)

update test3 set uage=100 where id=27
delete from test3 where id=20

可自己采用下面的查询踪两个表的数据变化:
select * from test3
select * from test3_bak

冯立彬的博客

人气教程排行