总结 output 用法

第一种用法

返回受 INSERT、UPDATE 或 DELETE 语句影响的每行的信息,或者返回基于上述每行的表达式。这些结果可以返回到处理应用程序,

以供在确认消息、存档以及其他类似的应用程序要求中使用。此外,也可以将结果插入表或表变量。

用于:

DELETE

INSERT

UPDATE

语法:

<OUTPUT_CLAUSE> ::=
{
    [ OUTPUT <dml_select_list> INTO { @table_variable | output_table } [ ( column_list ) ] ]
    [ OUTPUT <dml_select_list> ]
}
<dml_select_list> ::=
{ <column_name> | scalar_expression } [ [AS] column_alias_identifier ]
    [ ,...n ]

<column_name> ::=
{ DELETED | INSERTED | from_table_name } . { * | column_name }

--先创建一个表
create table test2(
[no] int ,
n nvarchar(100)
)
--插入测试数据
 insert into test2([no],n)
select 1,'a'
union
select 2,'b'
union
select 3,'c'
go

--插入数据时调用
--把插入数据显示出来
INSERT test2([no],n)
OUTPUT INSERTED.*
VALUES (4, N'd');
GO

select * from test2
go


DECLARE @MyTableVar table(
[no] int ,
n nvarchar(100)
);

--把[no]=1的记录删除,并把删除结果保存到表变量@MyTableVar中
delete from test2
output deleted.*
into @MyTableVar
where [no]=1

select * from @MyTableVar

select * from test2


DECLARE @MyTableVar table(
Newno int ,
Newn nvarchar(100),
Oldno int ,
Oldn nvarchar(100)
);

-- 修改记录,保存修改前后的记录到表变量中
update test2
set n='ccc'
output
    inserted.no,
    inserted.n,
    deleted.no,
    deleted.n
into @MyTableVar
where [no]=3

select * from @MyTableVar

select * from test2

第二种用法

declare @largestMonth nvarchar(10)

declare @strsql nvarchar(1000) 
 Set @strsql = "SELECT  @largestMonth=convert(nvarchar(10),MAX([Time]),120)"
 Set @strsql =@strsql + " FROM tablename"
 
 Set @strsql =@strsql + @filter
 exec sp_executesql @strsql,N'@largestMonth nvarchar(10) output',@largestMonth output

第三种用法

create procedure sp_output  
  @output int output  
 as  
  set @output = 121 
  return 1 

declare @out int   
 declare @count int 
 exec @count = sp_output @out output   
 select @count 
select @out

原文地址:https://www.cnblogs.com/wanglg/p/4043866.html