永久关闭

有了开始就有了好兆头,接受新生活也就是接受挑战。
我是一个普通的程序员,在这里开始写下程序人生的苦辣酸甜。

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::


1.局部变量
声明单个局部变量
declare @num int
声明多个局部变量

declare   @FirstName nvarchar(20)
               
@LastName nvarchar(20)
               
@Age  int

局部变量赋值
被赋值的局部变量必须是已经声明的。
a.简单赋值方法

declare @UserName varchar(10)
set @UserName = 'Niyo Wong'

b.使用select语句赋值

delcare @NoOfRecords int
set @NoOfRecords = (select count(*from tableName)
select @NoOfRecords = 20
declare @UserName  varchar(20)
declare @UserId  varchar(10)
select @UserName = userName from tbl_User where userId = '123401'
select @UserId = max(UserId) from tbl_User

注意:如果查询返回了多个值时,那么只有最后一个值赋给了变量。
c.使用update语句赋值

declare @qyt tinying
update tableName set @qty = fieldName where id = '1'

注意:update无法象select语句一样魏数据提供一些常用的转换,所以在使用update进行赋值时,
最好严格匹配数据类型,否则会产生错误。
2.全局变量
下面列举几个我们在编程中常用的全局变量
a. @@CURSOR_ROWS
返回本次服务器连接中,打开游标取回的数据行的数目。如:

select @@CURSOR_ROWS
declare employee_cursor cursor for
select emplid from tbl_Employee
open employee_cursor
fetch next from employee_cursor
select @@CURSOR_ROWS
close employee_cursor
deallocate employee_cursor

b. @@ERROR
返回上一条语句返回的错误号,执行成功返回0,
一般在insert,update,delete语句之后使用(常结合事务处理)。
c. @@FETCH_STATUS
返回上一次使用游标FETCH操作所返回的状态值。返回值为0表示操作成功,
为-1表示操作失败或者已经超过了游标所能操作的数据行的范围,当到了最后一行数据后,
还要接着取下一列数据,返回-2,表示返回值已经丢失。
d. @@ROWSCOUNT
返回上一条SQL语句所影响到的数据行的数据。常用于检查操作是否达到了目的,
当执行的SQL语句不影响数据库数据时,该变量返回0
e. @@VERSION
返回版本号
3.结构语句
a.条件结构
if.... else ...如:

if((select count(*from table1) > 0)
begin
 
declare @num int
 
set @num = (select max(no) from tabl2)
 
if(@num >(select count(*from table1))
 
begin
  
print '@num >(select count(*) from table1)'
 
end
 
else
  
if(@num = (select count(*from table1))
  
begin
   
print '@num = (select count(*) from table1)'
  
end
end
else
begin
 
print 'No of record below zero'
end

b.循环结构
while 语句。如:

declare @count int
set @count = 0
while(@count < 10)
begin
 
print @count
 
set @count = @count + 1 
end

在循环中常用的语句有break和continue,
break为跳出while,而continue为跳出当前循环,进入下一循环。
有时候也用到return和goto语句,下面我们将讲这两个语句。
c.case语句
case语句又叫条件分支语句。如:

select case userType 
 
when '1' then 'admin' 
 
when '2' then 'general user' 
 
else 'other' end 'userType' 
from tbl_user

或者


select 'userType' = case
  
when USERiD = '1' then 'admin'
  
when userName = 'Lucy' then 'admin'
  
when userType = '1' then 'admin'
  
when userType = '2' then 'general user'
  
else 'other' end
from tbl_user

注意:case语句中when匹配成功后,就到end,不会匹配下一个when,
所以如果有一条记录,userid = '1' 并且usertype = '2',
则返回uertype是‘admin'而不是’general user'

d.return语句
立即退出程序,return后面的语句将不执行。return 后常跟一个整形表达式作为返回值。
e.goto语句
跳转到跟在goto后面的标签位置。如

declare @count int
              
@value int
set @count = (select count(*from table)
if(@count = 0)
begin
    
set @value = 0
    
goto Flag
end
set @value = @count + 10
Flag:
print @value

以后将相继推出触发器,存储过程,游标及性能优化

posted on 2007-08-20 22:42  Niyo Wong  阅读(2072)  评论(1编辑  收藏  举报