T_sql简单语法知识

来源:互联网 发布:淘宝好评返现卡 编辑:程序博客网 时间:2024/05/22 11:46
 一:简单的语法知识
  1:定义变量给变量赋值
  2:if和else
  3:begin和end
  4:两种case语句
  5:循环
  http://www.cnblogs.com/liulun/articles/1359567.html
 

简单的语法知识

1 先举个例子


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


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语句


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语句


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的存在


use xland
if not exists(select id from mytable)
   
print '没?有?检?索?到?数?据?'
else
   
begin
       
select id from mytable
       
print cast(@@rowcount as varchar)+'行?被?检?索?到?'
   
end

上面语句执行结果是:2行被检索到

原创粉丝点击