您的位置:首页 > 数据库

SQL入门经典(七) 之脚本和批处理

2016-06-29 21:03 267 查看
什么是脚本。我们前面学的CREATE TABLE <table name> ,USE <database name>这些都是脚本,为什么用脚本。脚本存储到文件中并且可以重复利用和提取的文件。

创建变量: DECLARE语句最常用的语法: DECLARE @<variable name> <variable type>[=value][[,@<variable name> <variable type>[=value]@<variable name> <variable type>[=value],[.....n]];

DECLARE @TotalCount int=0 --创建变量,并初始化值(sql server2008以下数据库报错)
select @TotalCount --输出0
SET @TotalCount=10--设置变量值为10
select @TotalCount --输出10
select @TotalCount=count(*) from dbo.test003
select @TotalCount --输出5

也可以创建TABLE。
DECLARE @temp Table
(
ID  int identity(1,1) primary key,
name  nvarchar(20) not null
)
insert into @temp values('test_1');
insert into @temp values('test_2');
select * from @temp
结果:下面截图




使用流程控制语句:

先创建数据表

USE panda
GO

CREATE TABLE test004
(
ID  INT identity(1,1)  primary key,
name  nvarchar(20) not null,
typeint  int
)


if....else:基本语法IF<boolean Expression><SQL statement>|BEGIN <code series> END [ELSE <SQL statement>|BEGIN <code series> END]其中的表达式几乎可以是任何布尔表达式.

declare @count int
set @count=0;
while(@count<100)
begin
set @count=@count+1;
if(@count%4=0)
insert into dbo.test004 values('test_'+convert(nvarchar(20),@count),0);
else
insert into dbo.test004 values('test_'+convert(nvarchar(20),@count),@count%4);
end


多条语句 :

if(boolen expression)
begin
--语句1
--语句2
--语句3
end  --多条语句绑在一起成一条语句


case:基本语法: CASE<input expresstion> WHEN <when expression> THEN <result expression>[.....][ELSE <result expression>] END

SELECT  ID,name, [state]= CASE typeint%4
when 1 then '发货'
when 2 then '签收'
when 3 then '退货'
ELSE
'未知' END
FROM dbo.test004




while 基本语法:WHILE <Boolen expression>|<sql statement> [begin <statement block>[break]<sql statement>|<statement block>[CONTINUE] end];

BREAK 是强制结束循环。CONTINUE 重新回到起点,停止当前循环。

declare @count int
set @count=0;
while(@count<100)
begin
set @count=@count+1;
insert into dbo.test004 values('test_'+convert(nvarchar(20),@count),@count/4)
end


waitfor : 基本语法:WAITFOR DELAY< 'time'> |TIME <'time'>

DELAY 参数指定等待的时间段,不能指定天数-只能指定小时数、秒数、允许延迟最长时间为24小时。因此,如下语句。WAITFOR DELAY '24:00'将运行WAITFOR 语句前的任何代码。然后达到waitfor语句停止24小时,之后继续执行下一条语句。

TIME 参数参数指定等待的时间段,不能指定日期,只能是24小时制某个时间,同样最长延迟时间也是一天。因此,如下语句。WAITFOR TIME '00:00'将运行WAITFOR 语句前的的任何代码,直到凌晨0点停止执行。之后执行waitfor语句后下一条代码。

结束语:因为知识有限,还加上初学者,这章博客写的不怎么好,以后有时间在修改。和重新写,有写地方描述着不怎么清晰。。。以后会更新。。。下一章博客是存储过程。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: