1 先举个例子
Code
use myshop
declare @ident int
insert into orders
(customerid,orderdate)
values
(25,dateadd(day,-1,getdate()))--当前时间减去1天,就是昨天
select @ident = @@identity
insert into details
(orderid,productid,unitprice,quantity)
values
(@ident,1,50,25)
select 'the orderid of the inserted row is' + convert(varchar(8),@ident)
把数据插入定单表,得到新插入的记录的id然后插入定单明细表
2 定义变量给变量赋值
declare @myval int;
set @myval = 10;
set @myval1 = @myval2*12;
--下面语句是在查询中赋值变量
select @myval = max(id)+1 form mytable
3 if和else
Code
use xland
if not exists(select id from mytable)
print '暂时没有数据'
else
print cast(@@rowcount as varchar)+'被检索到'
上面语句执行结果是 0行被检索到
4 begin和end
如果条件内部要跟代码块(多条语句)
就要用到begin和end
5 case语句
第一种case语句
Code
use AdventureWorks
select SalesOrderID ,Position = Case SalesOrderID%10
when 1 then 'First'
when 2 then 'Second'
when 3 then 'third'
else 'some thing else'
end
from Sales.SalesOrderHeader
第二种case语句
Code
use AdventureWorks
select SalesOrderID ,Position = Case
when SalesOrderID%10 = 1 then 'First'
when SalesOrderID%10 = 2 then 'Second'
when SalesOrderID%10 = 3 then 'third'
else 'some thing else'
end
from Sales.SalesOrderHeader
第一种CASE when子句中可以跟表达式
第二种case when子句中表达式要返回true 或者false
当前面的条件和后面的条件同时满足时
按前面的条件处理,不需要break语句
6 循环语句
while 1=1
begin
waitfor time '01:00'
update mytable set num = 12 where id = 13
end
上面语句是在每天凌晨1点执行指定的操作
while允许break和continue的存在
Code
use xland
if not exists(select id from mytable)
print '没?有?检?索?到?数?据?'
else
begin
select id from mytable
print cast(@@rowcount as varchar)+'行?被?检?索?到?'
end
上面语句执行结果是:2行被检索到