使用新行在SQL中预填充外键

时间:2013-05-27 10:46:36

标签: sql tsql sql-server-2012 azure-sql-database

我正在尝试编写一个SQL脚本,该脚本将通过一个包含新创建的FK的表并使用外表中的新行预填充该键。我不是100%关于如何做到这一点,或者如果它在一个声明中是可能的,但这是我的尝试:

UPDATE [dbo].[Blogs]
set AuthorSecurableId = inserted.Id
FROM  [dbo].[Blogs] updating
INNER JOIN 
    (INSERT INTO [dbo].[Securables] (Name) 
     OUTPUT Inserted.id, ROW_NUMBER() OVER (ORDER BY Inserted.Id) as rownum
        SELECT 'Admin : ' + Name
        FROM Blogs
        WHERE AuthorSecurableId is null) inserted ON ROW_NUMBER() OVER (ORDER BY updating.Id) = inserted.rownum 
WHERE updating.AuthorSecurableId is null

当我这样做时,我收到以下错误

  

Msg 10727,Level 15,State 1,Line 5
  JOIN或APPLY运算符的任何一侧都不允许嵌套的INSERT,UPDATE,DELETE或MERGE语句。

下面是我所拥有的架构的简单视图

enter image description here

我想为每个没有博客的博客创建一个保证,并使用新创建的安全的AuthorSecurableId填充该博客ID

我想我可以用光标做到这一点,但我想知道是否有更好的单一陈述方法

1 个答案:

答案 0 :(得分:2)

您可以对Securables使用合并,输出到表变量或临时表,并对Blogs进行单独更新。

declare @T table
(
  SecID int,
  BlogID int
);

merge Securables T
using (
      select 'Admin : '+B.Name as Name, B.Id
      from Blogs as B
      where B.AuthorSecurabledId is null
      ) as S
on 0 = 1
when not matched by target then
  insert (Name) values (S.Name)
output inserted.Id, S.Id
  into @T;

update Blogs
set AuthorSecurabledId = T.SecID
from @T as T
where Blogs.Id = t.BlogID;

SQL Fiddle

相关问题