当前位置:Gxlcms > 数据库问题 > TSql Output 用法

TSql Output 用法

时间:2021-07-01 10:21:17 帮助过:5人阅读

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 } | $action

--$action 仅可用于 MERGE 语句

注释:output 将结果输出到客户端,output into 将结果输出到指定的表中。在一次查询中,output 和ouput into 可以同时出现,但是最多出现一次。

详细信息,参见:https://msdn.microsoft.com/zh-cn/library/ms177564.aspx 

示例代码

create table dbo.FinanceMonth
(MonthNum int ,
quantity int
)

;with cte as
(
    select 1 as MonthNum,100 as quantity
    union all
    select MonthNum+1,quantity+100
    from cte
    where MonthNum<12
)
insert into dbo.FinanceMonth
select *
from cte

第二部分:Output作为数据类型

1,创建一个stored procedure

ALTER PROCEDURE [dbo].[usp_test]
    @RowCnt int output
AS
BEGIN
    SET NOCOUNT ON;

    select @RowCnt= count(*)
    from dbo.FinanceMonth
END

2,执行stored procedure

declare @RowNum int
exec dbo.usp_test @RowNum output
print @RowNum

第三部分:用于返回结果

1,返回delete的数据到临时表中,删除的数据临时存储在deleted系统表中,该表是只读的,作用域是语句级别的,只存在于该delete语句中。

if object_id(tempdb..#tempFiM) is not null
drop table #tempFiM

select top 0 *
into #tempFiM
from dbo.FinanceMonth


delete dbo.FinanceMonth 
output deleted.* 
into #tempFiM
where MonthNum<3

select * 
from #tempFiM

2,返回insert的数据到临时表中,增加的数据临时存储在inserted系统表中,该表是只读的,作用域是语句级别的,只存在于该inserted语句中。

if object_id(tempdb..#tempFiM) is not null
drop table #tempFiM

select top 0 *
into #tempFiM
from dbo.FinanceMonth


insert into dbo.FinanceMonth 
output inserted.* 
into #tempFiM
select *
from dbo.FinanceMonth 
where MonthNum<4

select * 
from #tempFiM

3,update语句对数据进行修改,修改之前的数据存储在临时表deleted中,修改之后的数据存储在临时表inserted中,使用output语句可以将系统表inserted或deleted中的数据输出,但是一条update语句最多使用一次 output into子句。

if object_id(tempdb..#tempFiM) is not null
drop table #tempFiM

select top 0 *
into #tempFiM
from dbo.FinanceMonth


update dbo.FinanceMonth set quantity=quantity+1 
output deleted.* 
into #tempFiM
output inserted.* 
where MonthNum<4


select * 
from #tempFiM

 

TSql Output 用法

标签:

人气教程排行