现在的位置: 首页 > 综合 > 正文

数据库笔记四——数据库语言基础

2013年01月12日 ⁄ 综合 ⁄ 共 1249字 ⁄ 字号 评论关闭

SQL(Structured  Query Language)结构化查询语言, 是一种组织、管理和检索计算机数据库存储的数据的工具。

简单操作的举例:

 1、为局部变量赋值

 

use  student
declare @songname char(10)
select @songname=课程内容 from course where 课程类别='艺术类'
print @songname

select语句赋值和查询不能混淆,例如声明一个局部变量并赋值的SQL语句如下:

 

declare @b int
select @b=1

另一种局部变量的赋值方式是使用set语句:

declare @song char(20)
set @song='I love flower'

2、全局变量应用举例:

在pubs数据库中修改“authors”数据表时,用@@error检测限制查询冲突

use pubs
go
update anthors set an_id='172 32 1176'
where au_id='172-32-1176'
if @@error=547
  print'a check constraint violation occurred'

3、取余运算:

求2对5取余:

declare @x int,@y int,@z int
select @x=2,@y=5
set@z=@x%@y
print@z

注意:取余运算两边的表达式必须是整型数据

4、比较运算

查询打折之后价格仍大于12美元的书代号:

use pubs
go
select title_id as 书号,type as 种类,price as 价格
from title
where price-price*0.2>12

5、逻辑运算

use  student
select *
from student
where 性别='女' and 年龄>21

6、begin..end

完成两个变量交换:

declare @x int,@y int,@t int
set @x=1
set @y=2
begin
set @t=@x
set @x=@y
set @y=@t
end
print @x
print @y

7、if

判断一个数是否是正数

declare @x int
set @x=3
if @x>0
print'@x是正数'
print'end'

8、if...else

判断象限

declare @x int,@y int
set @x=8
set @y=3
if @x>0
   if @y>0
     print'@x@y位于第一象限'
   else
     print'@x@y位于第四象限'
else
   if @y>0
      print '@x@y位于第二象限'
   else
      print'@x@y位于第三象限'

9、while

求1~10之间的和

declare @n int,@sum int
set @n=1
set @sun=0
while @n<=10
begin
set @sum=@sun +@n
set @n=@n +1
end
print @sum

10、return

declare @x int
set @x=3
if @x>0
print'遇到return之前'
return
print'遇到return之后'

执行后的结果是:遇到return之前

说明位于return之后的语句不会执行

 

 

抱歉!评论已关闭.