【问题标题】:Insert into SQL table using Loop使用 Loop 插入 SQL 表
【发布时间】:2017-08-21 17:33:25
【问题描述】:

我有两张桌子

  • Chapters_tbl(儿童 ID、姓名)
  • Status_tbl (chID, Ch_status)

对于Chapters_tbl 中的每个chID,我想将chID 插入到Status_tblCh_status

我可以在 C# 中使用 SQL Server 存储过程或实体框架。

我该怎么做?

【问题讨论】:

  • Microsoft 的文档展示了如何同时使用 EF 和 SQL 来执行插入操作; this article 专门讲了如何使用 map EF 调用到存储过程中。

标签: sql-server entity-framework stored-procedures


【解决方案1】:

使用 T-SQL...

INSERT dbo.Status_tbl (chID, Ch_status)
SELECT 
    c.chID,
    Ch_status = 1
FROM 
    dbo.Chapters c
WHERE 
    NOT EXISTS (
                SELECT 1 
                FROM dbo.Staus_tbl s 
                WHERE c.chID = s.chID
                );

【讨论】:

  • 这里的 c 是什么,Ch_status 值不是来自其他表,它是 1
  • "c" 是 Chapters 表的表别名。至于 Ch_status 评论...您 OP 声明,“我想在 Status_tbl 和 Ch_status 中插入该 chID”...我读为“我希望将 chID 插入两列...我已经更新了我的答案在该列中插入 1。
猜你喜欢
  • 2013-02-17
  • 1970-01-01
  • 1970-01-01
  • 2021-09-21
  • 2013-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-25
相关资源
最近更新 更多