[英]How do I make sure OUTPUT INSERTED is in correct order?
Let's say I have this @TempTable
with only 2 columns ProductName
and TempID
: 比方说,我有这个
@TempTable
只有2列ProductName
和TempID
:
ProductName | TempID
------------+------
GTX 1080 | NULL
GTX 1080Ti | NULL
RX 580 | NULL
I will insert this to TblProduct
(2 columns: ProductName
and ID
) with the following command: 我将使用以下命令将其插入
TblProduct
(2列: ProductName
和ID
):
INSERT INTO TblProduct (ProductName)
OUTPUT INSERTED.ID INTO @Test123(ID)
SELECT ProductName
FROM @TempTable
Is it guaranteed that the output result in @Test123
is in correct order? 是否可以确保
@Test123
中的输出结果顺序正确? Meaning that if the result is 1, 2, and 3. 表示如果结果是1、2和3。
Is it possible to update TempID
in @TempTable
from ID
in @Test123
? 是否可以从
@Test123
ID
更新TempID
中的@TempTable
? If yes, how? 如果是,怎么办? I was thinking of something like
UPDATE ... SELECT ...
我在想类似
UPDATE ... SELECT ...
No, it's not guaranteed at all. 不,完全不能保证。
Tables in a relational database are unsorted by nature - in other words - the records have no inherent order. 关系数据库中的表不是按性质排序的,换句话说,记录没有固有的顺序。
However, you can output more than one column using the output clause, so for your sample data, you could output both ProductName
and ID
(of course, this means that the table variable @Test123
must have (at least) these two columns): 但是,您可以使用output子句输出多个列,因此对于示例数据,您可以同时输出
ProductName
和ID
(当然,这意味着表变量@Test123
必须(至少)具有这两列):
INSERT INTO TblProduct (ProductName)
OUTPUT INSERTED.ID, INSERTED.ProductName INTO @Test123(ID, ProductName)
SELECT ProductName
FROM @TempTable
If you want the rows to appear in alphabetical order, as in your example then say: 如果要使行按字母顺序显示(如您的示例),请说:
select ProductName
from TblProduct
order by ProductName;
If you want some other order then you need a column that defines that order so that you can put the appropriate order on the select statement. 如果需要其他顺序,则需要定义该顺序的列,以便可以在select语句上放置适当的顺序。 For example, if you want to get the rows back in the order you inserted them, define your table as:
例如,如果要按插入顺序返回行,则将表定义为:
create table TblProduct
(
id int identity(1,1) not null,
ProductName varchar(20),
tempID int
);
then 然后
select ProductName
from TblProduct
order by id;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.