【问题标题】:Insert data in relationship table without identity_insert ON在没有 identity_insert ON 的关系表中插入数据
【发布时间】:2011-12-16 23:23:35
【问题描述】:

我有一个场景,我必须使用脚本将一些主数据插入到表中,以便我们可以在部署时在生产服务器上使用此脚本。

我的桌子是

Category
 --Id (PK, Identity)
 --Name

CategoryType
  --Id (PK, Identity)
  --Name
  --CategoryID (FK) 

现在我在 excel 中有一些用于类别和类别类型的行数据。 我必须生成数据脚本(一组插入语句)。

我做了什么

Start with  identity_insert ON 
insert statement for Category table
Insert statement for CategoryType table with respect of category PK
end  identity_insert Off

我只是想知道有什么办法可以避免 identity_insert ON/OFF 的事情。

【问题讨论】:

    标签: sql-server identity-insert


    【解决方案1】:

    也许这就是你要找的东西:

    DECLARE @inserted table ( id int ) --assuming ID is int
    
    INSERT INTO Category ( Name )
    OUTPUT INSERTED.Id INTO @inserted
    VALUES( 'MyCategory Name' )
    
    INSERT INTO CategoryType( Name, CategoryID )
    SELECT id, 'MyCategoryTypeName'
    FROM @inserted
    

    希望对你有帮助
    最好的问候,
    约旦

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-18
      • 1970-01-01
      相关资源
      最近更新 更多