当前位置: 首页 > 图文教程 > 数据库 > MSSQL > MSSQL2005 INSERT,UPDATE,DELETE 之OUTPUT子句使用实例

MSSQL
SQL Server--全文本检索的应用(一)
SQL 2005的SSIS与Oracle的迁移性能
SQL优化实例:从运行30分钟到运行只要30秒
无法在SQL Server2005 Manger Studio 中录入中文的问题
SQL Artisan多表查询和统计
SQL Server数据库开发人员在应聘时经常被问到哪些问题
一个完整的SQL SERVER数据库全文索引的示例
SQL Server安全之加密术和SQL注入攻击
如何对SQL Server中的tempdb“减肥”
SQL Server 2005升级的十个步骤
如何在SQL Server开发中融入极限编程技术
SQL Server应用程序高级SQL注入(下)
SQL Server应用程序高级SQL注入(上)
SQL Server连接中的常见错误
IIS中SQL Server数据库的安全问题
SQL Server 2005区域配置和安全工具
保护 SQL Server 的十个步骤
如何利用SQL Server 2000的复制选项
SQL Server 数据库使用备份还原造成的孤立用户和对象名‘xxx’无效的错误的解决办法
SQL SERVER 2005同步复制技术的应用

MSSQL2005 INSERT,UPDATE,DELETE 之OUTPUT子句使用实例


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2010-01-10   浏览: 128 ::
收藏到网摘: n/a

MSSQL2005 INSERT,UPDATE,DELETE使用实例,大家可以看下。
复制代码 代码如下:

-->Title:Generating test data
-->Author:wufeng4552
-->Date :2009-10-07 15:16:26
if object_id('ta')is not null drop table ta
go
create table ta(ID int identity,[name] varchar(10))
insert ta([name]) select 'a' union all
select 'b' union all
select 'c' union all
select 'd' union all
select 'e' union all
select 'f' union all
select 'g'
if object_id('tb')is not null drop table tb
go
create table tb(ID int identity,[name] varchar(10))
insert tb([name]) select 'a' union all
select 'b' union all
select 'c'
--INSERT 陳述式來使用 OUTPUT INTO
insert tb output
inserted.id,
inserted.[name]
select [name]
from ta where not exists(select 1 from tb where [name]=ta.[name])
/*
id name
----------- ----------
4 d
5 e
6 f
7 g
*/
--刪除剛才插入的紀錄
delete tb where [name]>'c'
--储存此结果集保存到一个表值变量中
declare @t table(ID int,[name] varchar(10))
insert tb output
inserted.id,
inserted.[name]into @t
select [name] from ta where not exists(select 1 from tb where [name]=ta.[name])
select * from @t
/*
ID name
----------- ----------
8 d
9 e
10 f
11 g
(4 個資料列受到影響)
*/
--DELETE 陳述式使用 OUTPUT
delete tb output deleted.* where id=9
/*
ID name
----------- ----------
9 e
(1 個資料列受到影響)
*/
-- UPDATE 陳述式使用 OUTPUT INTO
update tb set [name]='test' output inserted.* where id=10
/*
ID name
----------- ----------
10 test
(1 個資料列受到影響)
*/
/*
OUTPUT 子句对于在 INSERT操作之后检索标识列或计算列的值可能非常有用。
另外OUTPUT子句也可以在UPDATE和DELETE语句中使用,从插入表或删除表中得到数值,并返回这些数值。
以下语句中不支持 OUTPUT 子句:
l 引用本地分区视图、分布式分区视图或远程表的 DML 语句。
l 包含 EXECUTE 语句的 INSERT 语句。
l 不能将 OUTPUT INTO 子句插入视图或行集函数。
简洁的OUTPUT子句,使得向SQL Server导入数据的操作得到了极大的简化。