简体   繁体   English

输出子句解释

[英]Output Clause Explained

请向我解释 SQL Server 输出子句。

Do some examples help?一些例子有帮助吗? The below all output the result to the client but you can also OUTPUT INTO a @table_variable (or a standard table under certain conditions)以下都将结果输出到客户端,但您也可以OUTPUT INTO a @table_variable (或某些条件下的标准表)

create table T
(
id int identity(1,1),
c char(1)
)

insert into T(c) 
OUTPUT inserted.* /*Output Inserted Rows - shows the ids that were allocated*/
values ('A'),('B'),('C')

Returns退货

id          c
----------- ----
1           A
2           B
3           C

. .

UPDATE T
SET c = CHAR(ASCII(c)+1)
 /*Output before and after versions of each row*/
OUTPUT deleted.*, inserted.*
WHERE id IN (2,3)

Returns退货

id          c    id          c
----------- ---- ----------- ----
2           B    2           C
3           C    3           D

. .

DELETE 
FROM T
 /*Output the row(s) that were deleted*/
OUTPUT deleted.*
WHERE DATEPART(second, getdate())%id = 0

Returns (for example)退货(例如)

id          c
----------- ----
1           A

Edit:编辑:

In response to comment some examples showing how OUTPUT can be used to insert to a table.作为对评论的回应,一些示例显示了如何使用OUTPUT插入表。

CREATE TABLE #T2
(
id UNIQUEIDENTIFIER DEFAULT NEWSEQUENTIALID(),
c CHAR(1)
)

DECLARE @inserted TABLE
(
id UNIQUEIDENTIFIER,
c CHAR(1)
)

INSERT INTO #T2(c) 
OUTPUT inserted.id, inserted.c 
INTO @inserted
VALUES ('A')

If you are on SQL Server 2008 you can use composable DML如果您使用的是 SQL Server 2008,则可以使用可组合 DML

INSERT INTO @inserted
SELECT I.id, I.c
FROM 
    (
    INSERT INTO #T2(c) 
    OUTPUT inserted.id, inserted.c 
    VALUES ('B'),('C')
    ) AS I
WHERE c <> 'C' --Only add rows of interest to @inserted table

But you will get an error message if the insert target participates in a PK/FK relationship.但如果插入目标参与 PK/FK 关系,您将收到错误消息。 If you encounter this problem you can also use this pattern . 如果您遇到此问题,您也可以使用此模式

INSERT INTO @inserted
EXEC sp_executesql N'
    INSERT INTO #T2(c) 
    OUTPUT inserted.id, inserted.c 
    VALUES (''D''),(''E'') '

It could be stated as可以表述为

How do I find out what rows were deleted, inserted or updated?如何找出哪些行被删除、插入或更新?

You can using some fancy trigger code or a separate SELECT, but the OUTPUT clause make it effortless.您可以使用一些花哨的触发代码或单独的 SELECT,但 OUTPUT 子句使其毫不费力。 The SELECT becomes part of the actual DELETE, INSERT or UPDATE SELECT 成为实际 DELETE、INSERT 或 UPDATE 的一部分

The OUTPUT clause allows you to combine an INSERT or UPDATE with a SELECT . OUTPUT子句允许您将INSERTUPDATESELECT结合使用。

You can OUTPUT a list of fields, and the query will return one row for each row affected by the INSERT / UPDATE .您可以OUTPUT字段列表,查询将为受INSERT / UPDATE影响的每一行返回一行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM