sql server 2008学习9 编写脚本和批处理

查看最后一行插入标识列的值

use test
go
insert into a(name) values('ss')
declare @ident int
select @ident=@@identity
select @ident
结果: 

image

查看语句响应了多少行

use test 
go
declare @rowCount int
select * from b
select @rowCount=@@rowcount
select @rowCount
效果如图:
image

批处理:

使用go可以将一个脚本,分为多个批处理

下面脚本创建一个表,

if not exists(
        select s.name,t.name from sys.schemas s 
        join sys.tables t on s.[schema_id]=t.[schema_id] 
        where s.name='dbo' and t.name='d')
    begin
        print 'table is not found .';
        print 'creating: table dbo.d';
        create table d( col1 int primary key);
    end
else
    print 'the table is exist'

运行结果:

image   image

case语句

简单case:
select top 5 

id,tem= case id%5 
          when 1 then 'first'
           when 2 then 'second'
            when 3 then 'third'
            else 'none'
             end
from b

结果:

image

搜索case语句:

于简单case的不同之处:

  1. 没有 case  和when之间的 表达式
  2. when表达式必须判断 为一个布尔值

搜索case最棒的地方就是  可以完全更改构成表达式基础的内容.

select top 9 
RowNumber,"info?"=case 
        when LoginName='sa' then '这是管理员登陆'
         when Duration>100 then '执行效率很低'
         else ' 没有匹配项'
         end
from dbo.test1

结果:

image

当 LoginName 有值的时候,走 when LoginName='sa' then '这是管理员登陆' 这句,当LoginName为null的时候,才走when Duration>100 then '执行效率很低'   如果两列都没值,那么就 直走 else了

waitfor 语句

有两种结构:

一种是定时,一种是延迟

延迟的:

insert into a(name) values('1')
waitfor delay '00:01'   延迟1分钟执行下面的语句
insert into a(name) values('2')

效果如图:看 右下角红圈的地方,

image

定时:

select getdate()
waitfor time '16:17' 
insert into a(name) values('3')

如图:

image

image

原文地址:https://www.cnblogs.com/soundcode/p/2680000.html