星空网 > 软件开发 > 数据库

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

什么是脚本。我们前面学的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 --输出0SET @TotalCount=10--设置变量值为10select @TotalCount --输出10select @TotalCount=count(*) from dbo.test003select @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结果:下面截图

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

使用流程控制语句:

先创建数据表

USE pandaGOCREATE 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  --语句3end --多条语句绑在一起成一条语句

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

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

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语句后下一条代码。

结束语:因为知识有限,还加上初学者,这章博客写的不怎么好,以后有时间在修改。和重新写,有写地方描述着不怎么清晰。。。以后会更新。。。下一章博客是存储过程。




原标题:SQL入门经典(七)之脚本和批处理

关键词:sql

sql
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

广东出发去大洋洲旅游:https://www.vstour.cn/t/广东出发去大洋洲旅游.html
广东出发去岱山岛旅游:https://www.vstour.cn/t/广东出发去岱山岛旅游.html
广东出发去丹麦旅游:https://www.vstour.cn/t/广东出发去丹麦旅游.html
广东出发去德国旅游:https://www.vstour.cn/t/广东出发去德国旅游.html
广东出发去地中海邮轮旅游:https://www.vstour.cn/t/广东出发去地中海邮轮旅游.html
广东出发去迪拜旅游:https://www.vstour.cn/t/广东出发去迪拜旅游.html
珠海长隆横琴剧院票价是多少:https://www.vstour.cn/a/335166.html
珠海长隆横琴剧院交通指引:https://www.vstour.cn/a/335167.html
相关文章
我的浏览记录
最新相关资讯
跨境电商服务平台 | 深圳旅行社 | 东南亚物流