Jandren

  博客园 :: 首页 :: 新随笔 :: 联系 :: :: 管理 ::

一,先来举个例子

--将数据插入定单表tb_orders,

得到新插入的记录的id然后插入定单明细表tb_orderdetail

declare @ident int
insert into tb_orders(CustomerId,orderdate)

values(25,dateadd(day,-1,getDate())) --当前时间减去1天,就是昨天
select @ident = @@identity
insert into tb_orderdetail(OrderId,ProductId,UnitPrice,Quantity)
values(@ident,1,50,25)
select 'the orderid of the inserted row is ' + convert(varchar(8),@ident) --返回插入记录的id

 

二,定义变量并给变量赋值及自定义自动增长id
declare @myval int
select @myval = IsNull(max(id),0)  from tb_orders
set @myval = @myval+1
select @myval as MyId   --显示id

 

三,if...else..用法

  如果条件内要用到代码块(多条语句)

  就要用到(begin与end)

if not exists(select id from tb_orders)
 print '暂时没有数据';
else
 begin
   select id from tb_orders
   print cast(@@rowcount as varchar)+'行被检索到'
 end

四,Case语句 

--第一种Case语句用法
select id,CustomerId = Case id/2
When 1 then 'Second'
When 2 then 'Four'
else
 'some thing else'
end
From tb_orders

--第二种Case语句用法
select id,CustomerId = Case
When id/2 = 1 then 'Second'
when id/2 = 2 then 'Four'
else
 'some thing else'
end
From tb_orders

--第一种Case...When子句中可以跟表达式
--第二种Case...When子句中的表达式要返回true或false
--当前面的条件满足时再执行then语句
--不需要break语句

五,--循环语句
while 1=1
begin
 waitfor time '09:31'
        update tb_orderdetail set Quantity = 42 where id = 1
 break;
end

--上面语句是在每天凌晨1点30分执行指定的操作
--while允许break和continue的存在

  

posted on 2010-07-05 15:22  Jandren  阅读(210)  评论(0)    收藏  举报