[英]How to use OUTPUT clause of SQL Server for update
DECLARE @t2 AS TABLE(id INT)
INSERT INTO dbo.EntityMaster
(EntityType)
OUTPUT INSERTED.EntityId INTO @t2
SELECT 'G' FROM #tmp
#tmp
is a temporary table that contains data loaded from an xml. #tmp
是一个临时表,包含从xml加载的数据。 I need to generate EntityId
for each record contained in #tmp
. 我需要为#tmp
包含的每条记录生成EntityId
。 It can be done by inserting record first into EntityMaster
table then insert this entityid back into #tmp
for each record. 可以先将记录插入到EntityMaster
表中,然后将此实体代码插入到每个记录的#tmp
中。
Instead of inserting record into @t2
, I need to update #tmp
for each record. 我没有将记录插入@t2
,而是需要为每条记录更新#tmp
。
Any possibility? 有可能吗?
Try Something like this, you still have to use the temp table but it's not too bad to read and it gets the job done. 尝试像这样的东西,你仍然需要使用临时表,但它不是太糟糕的阅读,它完成工作。
CREATE TABLE #tmp ( tmpID INT IDENTITY(1,1) PRIMARY KEY CLUSTERED, xmlData VARCHAR(255), EntityId INT ) DECLARE @t2 TABLE ( tmpID INT, EntityId INT ) MERGE dbo.EntityMaster AS EM USING ( SELECT tmpID, xmlData, EntityId FROM #tmp ) AS X ON EM.EntityId = X.EntityId WHEN NOT MATCHED THEN INSERT (EntityType) VALUES (X.xmlData) OUTPUT X.tmpID, INSERTED.EntityId INTO @t2 (tmpID, EntityId); UPDATE T SET EntityId = T2.EntityId FROM @t2 T2 INNER JOIN #tmp T ON T2.tmpID = T.tmpID
This would be easier to accomplish in the SQL that inserts the XML records into the #tmp
table. 在将XML记录插入#tmp
表的SQL中,这将更容易实现。
Consider the following @recs
table, which could be thought of as a set of records generated from XML: 考虑以下@recs
表,可以将其视为从XML生成的一组记录:
declare @recs table (val varchar(255))
insert into @recs values ('this'), ('is'), ('a'), ('test')
You can easily add an incrementing integer to each record like this: 您可以轻松地为每条记录添加递增整数,如下所示:
select row_number() over (order by (select 1)) as id, val from @recs
The result looks like this: 结果如下:
id val
1 this
2 is
3 a
4 test
Could you use row_number() over (order by (select1))
to generate the ids you need at the same time the records are being inserted into #tmp
? 您可以使用row_number() over (order by (select1))
来生成在将记录插入#tmp
的同时需要的ID吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.