A Beginner’s Guide to the OUTPUT Clause in SQL Server

本文涉及的产品
RDS SQL Server Serverless,2-4RCU 50GB 3个月
推荐场景:
云数据库 RDS SQL Server,基础系列 2核4GB
简介: 原文 A Beginner’s Guide to the OUTPUT Clause in SQL Server T-SQL supports the OUTPUT clause after the inception of SQL server 2005 and later editions.

原文 A Beginner’s Guide to the OUTPUT Clause in SQL Server

T-SQL supports the OUTPUT clause after the inception of SQL server 2005 and later editions. We can use the OUTPUT clause with DML statements (INSERT, DELETE, UPDATE) to return information from modified rows.

 

We primarily use the OUTPUT clause for auditing and archiving modified rows. In this tutorial, we will walk through the use of the OUTPUT clause with different DML statements and examples. First, we will create a table, dbo.Songs, and populate it with some data.

IF OBJECT_ID('dbo.Songs') IS NOT NULL
DROP TABLE dbo.Songs
GO
CREATE TABLE dbo.Songs
(
Id int CONSTRAINT PK_Songs_Id PRIMARY KEY,
Name varchar(200) NOT NULL,
Singer varchar(50) NOT NULL
)
GO

INSERT INTO dbo.Songs ( Id, Name, Singer) 
VALUES (1, 'I hate everything about you', 'Adam Gontier');
INSERT INTO dbo.Songs ( Id, Name, Singer) VALUES (2, 'Dil se', 'A. R. Rahman');
INSERT INTO dbo.Songs ( Id, Name, Singer) VALUES 
(3, 'My heart will go On', 'Celine Dion');
INSERT INTO dbo.Songs ( Id, Name, Singer) VALUES (4, 'Maeri', 'Euphoria');
GO

SELECT * from dbo.Songs
GO

 

SQL server Output Clause_1

 

Inserted and Deleted Tables in an OUTPUT Clause

Inserted and Deleted tables are two memory-resident tables that reside within SQL server and are used with the OUTPUT clause.

Whenever any DML (INSERT, DELETE, UPDATE) statement is executed, these tables are populated.

The results of the INSERT statement are stored in the Inserted table, and the results of the Delete statement are stored in the Deleted table. Also, with an UPDATE statement, the deleted rows are stored in the Deleted table. The new inserted rows in the Inserted table as UPDATE are nothing but delete and insert operations combined together.

Note: You cannot directly query Inserted and Deleted tables to see what data they are currently holding, but you can use them with the OUTPUT clause as well as with Triggers.

 

The OUTPUT Clause with an Insert statement

When we do an Insert operation on a table, we get a message which reads, “(n row(s) affected),” but if we want to see what data rows were inserted into a table, we can use an OUTPUT clause and a memory resident inserted table to return the results back to the screen in the same way that a select statement does.

Let us insert a record, and use an OUTPUT clause to print the results on the screen.

INSERT INTO dbo.Songs ( Id, Name, Singer)
OUTPUT INSERTED.ID, INSERTED.name, INSERTED.Singer
VALUES (5, 'AINT no grave', 'Johnny Cash');
GO


Check the dbo.Songs table. A new row is inserted with id=5.

select * from dbo.Songs;
GO

 

SQL server Output Clause_2

 

The OUTPUT Clause with a Delete Statement

The same goes with a delete operation. It shows only (n rows(s) affected). We can use an OUTPUT clause and a deleted table to see which rows were actually deleted from the table.

DELETE from dbo.Songs
OUTPUT DELETED.id, DELETED.name, DELETED.singer
WHERE ID=5;
GO


Query the dbo.Songs table row with id = 5 has been deleted.

select * from dbo.Songs;
GO

 

SQL server Output Clause_3

 

The OUTPUT Clause with an Update Statement

An Update statement does nothing but delete old data and insert new data, so with an Update statement, both memory resident tables are affected and are deleted as well as inserted.

Here we are updating the name of a singer, who has sung ‘Dil se’ song, with ID equal to two.

UPDATE dbo.Songs
SET Singer = 'Rahman'
OUTPUT DELETED.Singer, INSERTED.Singer
WHERE ID = 2;
GO


You can see the old singer’s name along with the new singer’s name.

select * from dbo.Songs;

 

SQL server Output Clause_4

The three examples above show how to use an OUTPUT clause for auditing purposes. Now, we will see how to use it for archiving.

Before, we were just printing the results of a DML statement on the screen, which was temporary, but with the OUTPUT clause, you can store the results of a DML statement in a table, too.

 

Store Results of an OUTPUT Clause into a Table

Inserting the data return from an OUTPUT clause into a table can be done using an OUTPUT INTO clause. Keep in mind that you first need to create the target table which must have the same number of columns and data types that match the source table.

IF OBJECT_ID('dbo.Songs_Inserted') IS NOT NULL
DROP TABLE dbo.Songs_Inserted
GO
CREATE TABLE dbo.Songs_Inserted
(
Id int CONSTRAINT PK_Songs__Inserted_Id PRIMARY KEY,
Name varchar(200) NOT NULL,
Singer varchar(50) NOT NULL
)
GO

INSERT INTO dbo.Songs ( Id, Name, Singer)
OUTPUT Inserted.* INTO dbo.Songs_Inserted 
VALUES (5, 'Duniya', 'Piyush Mishra');
GO

-- Result of Songs_Inserted table and base table.
select * from dbo.Songs_Inserted;
select * from dbo.Songs;
GO

 

SQL server Output Clause_5

As the results above show, data is inserted into both the tables.

 

Store Results of an OUTPUT Clause into a Temporary Table

The same goes with a temporary table. Create a temporary table first, and then using an OUTPUT INTO clause, insert the data returned by the OUTPUT clause into a temporary table.

IF OBJECT_ID('tempdb..#Songs_Deleted') IS NOT NULL
DROP TABLE dbo.#Songs_Deleted
GO
CREATE TABLE dbo.#Songs_Deleted
(
Id int,
Name varchar(200) NOT NULL,
Singer varchar(50) NOT NULL
)
GO

DELETE from dbo.Songs
OUTPUT deleted.* INTO dbo.#Songs_Deleted
WHERE ID IN (4,5);
GO

-- Result of temporary table and base table.
SELECT * from dbo.#Songs_Deleted;
Select * from dbo.Songs;

 

SQL server Output Clause_6

 

Store Results of an OUTPUT Clause into a Table Variable

Nothing changes for table variables as well. Declare a table variable structure the same as a source table. Do not forget to run the entire script at once so that you can see the output inserted into a table variable.

Declare @Songs_Deleted TABLE
(
Id int,
Name varchar(200) NOT NULL,
Singer varchar(50) NOT NULL
)

DELETE from dbo.Songs
OUTPUT deleted.* INTO @Songs_Deleted
WHERE ID IN (1,2);
-- Result of table variable

SELECT * from @Songs_Deleted;

 

SQL server Output Clause_7

Browse through our SQL server archive articles for more useful information.

相关实践学习
使用SQL语句管理索引
本次实验主要介绍如何在RDS-SQLServer数据库中,使用SQL语句管理索引。
SQL Server on Linux入门教程
SQL Server数据库一直只提供Windows下的版本。2016年微软宣布推出可运行在Linux系统下的SQL Server数据库,该版本目前还是早期预览版本。本课程主要介绍SQLServer On Linux的基本知识。 相关的阿里云产品:云数据库RDS SQL Server版 RDS SQL Server不仅拥有高可用架构和任意时间点的数据恢复功能,强力支撑各种企业应用,同时也包含了微软的License费用,减少额外支出。 了解产品详情: https://www.aliyun.com/product/rds/sqlserver
目录
相关文章
|
3月前
|
SQL 数据库
SQL 中的 CLAUSE 是什么?
【8月更文挑战第31天】
86 0
|
数据库
解决which is not functionally dependent on columns in GROUP BY clause;...sql_mode=only_full_group_by
解决which is not functionally dependent on columns in GROUP BY clause;...sql_mode=only_full_group_by
281 0
|
SQL 关系型数据库 MySQL
软件测试mysql面试题:SQL中的CLAUSE是什么?
软件测试mysql面试题:SQL中的CLAUSE是什么?
329 0
|
SQL 安全 OLAP
Installation Guide for SQL Server 2008 R2
Hi Folks, you might be wondering about the steps for the installation of SQL Server 2008 R2.
1040 0
|
2月前
|
关系型数据库 MySQL 网络安全
5-10Can't connect to MySQL server on 'sh-cynosl-grp-fcs50xoa.sql.tencentcdb.com' (110)")
5-10Can't connect to MySQL server on 'sh-cynosl-grp-fcs50xoa.sql.tencentcdb.com' (110)")
|
4月前
|
SQL 存储 监控
SQL Server的并行实施如何优化?
【7月更文挑战第23天】SQL Server的并行实施如何优化?
113 13
|
4月前
|
SQL
解锁 SQL Server 2022的时间序列数据功能
【7月更文挑战第14天】要解锁SQL Server 2022的时间序列数据功能,可使用`generate_series`函数生成整数序列,例如:`SELECT value FROM generate_series(1, 10)。此外,`date_bucket`函数能按指定间隔(如周)对日期时间值分组,这些工具结合窗口函数和其他时间日期函数,能高效处理和分析时间序列数据。更多信息请参考官方文档和技术资料。
|
4月前
|
SQL 存储 网络安全
关系数据库SQLserver 安装 SQL Server
【7月更文挑战第26天】
61 6