【问题标题】:Only insert data into a database if it doesn't exist already仅当数据库不存在时才将数据插入数据库
【发布时间】:2017-04-18 09:23:19
【问题描述】:

我正在尝试编写只允许我插入具有不同 ID 的记录的代码;如果数据库中已经存在相同的 ID,则不应插入该记录。

我的 SQL 代码是这样的:

SqlCommand cmd = new SqlCommand("insert into User(UserId,Name,Profession) values(@UserId,@Name,@Profession) WHERE NOT EXISTS (Select UserId From User where UserId = @UserId)", con);

但它不起作用,当我尝试这个时,没有任何东西添加到数据库中。 如何更正此查询?

谢谢,

【问题讨论】:

  • 尝试使用NOT IN。此外,当您使用 select 插入时,您需要删除值,因为您选择了所述值。
  • 请注意,这种方法本身并不能在所有情况下防止 userId 上的重复。

标签: c# sql-server database visual-studio


【解决方案1】:

而不是:

insert into User(UserId,Name,Profession) 
       values(@UserId,@Name,@Profession) 
       WHERE NOT EXISTS (Select UserId From User where UserId = @UserId)

使用这个查询:

insert into User(UserId,Name,Profession) 
       select @UserId, @Name, @Profession
       where not exists (Select UserId From User where UserId = @UserId)

说明:AFAIK 插入命令不能组合 VALUES 和 WHERE 子句。但是,您可以定义一个 SELECT 来指示要插入的值,而不是直接提供值(使用 VALUES 子句)。在该 SELECT 上,您现在可以使用过滤器、连接等...,因此您可以在那里定义您的过滤器,检查该行是否仍然存在。

【讨论】:

  • 如果你描述,为什么,这将是一个正确的答案:)
【解决方案2】:

试试这个:

SqlCommand cmd = new SqlCommand("IF NOT EXISTS (Select UserId From User where UserId = @UserId) insert into User(UserId,Name,Profession) values(@UserId,@Name,@Profession) ", con);

【讨论】:

    【解决方案3】:

    这与实现相同的 SQL 查询。

    IF NOT EXISTS (Select UserId From User where UserId = @UserId
    insert into User(UserId,Name,Profession) values(@UserId,@Name,@Profession)
    

    【讨论】:

      【解决方案4】:
      猜你喜欢
      • 1970-01-01
      • 2014-10-15
      • 2014-11-01
      • 2022-06-10
      • 1970-01-01
      • 1970-01-01
      • 2017-04-21
      • 1970-01-01
      • 2013-06-14
      相关资源
      最近更新 更多