sql-server - 如何以有效的方式覆盖数据库中的重复数据?

标签 sql-server database sql-server-2008 ado.net

我使用Sql server 2008来存储我的数据,表结构是这样的

index float  not null,
type int   not null,
value int  not null,

并且(索引,类型)是唯一的。没有两个数据具有相同的索引和相同的类型。

所以当我向表中插入数据时,我必须检查(索引,类型)对是否已经在表中,如果存在我使用更新语句,否则我直接插入它。但我认为这是不是一种有效的方法,因为:

  1. 大部分数据的索引类型对在表中是不存在的,所以选择操作是浪费,尤其是表很大。

  2. 当我使用C#或其他CLR语言插入数据时,无法使用批量复制或批量插入。

有没有办法不检查表中是否存在,直接覆盖数据?

最佳答案

如果你想更新或插入数据,你需要使用merge :

merge MyTable t using (select @index index, @type type, @value value) s on
    t.index = s.index
    and t.type = s.type
when not matched insert (index, type value) values (s.index, s.type, s.value)
when matched update set value = s.value;

这将查看您的值(value)观并采取适当的行动。

要在 C# 中执行此操作,您必须使用传统的 SqlClient:

SqlConnection conn = new SqlConnection("Data Source=dbserver;Initial Catalog=dbname;Integrated Security=SSPI;");
SqlCommand comm = new SqlCommand();
conn.Open();
comm.Connection = conn;

//Add in your values here
comm.Parameters.AddWithValue("@index", index);
comm.Parameters.AddWithValue("@type", type);
comm.Parameters.AddWithValue("@value", value);

comm.CommandText = 
    "merge MyTable t using (select @index index, @type type, @value value) s on " +
        "t.index = s.index and t.type = s.type " +
    "when not matched insert (index, type value) values (s.index, s.type, s.value) " +
    "when matched update set value = s.value;"
comm.ExecuteNonQuery();

comm.Dispose();
conn.Close();
conn.Dispose();

关于sql-server - 如何以有效的方式覆盖数据库中的重复数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8538193/

相关文章:

sql - 使用排列表来填补空白

sql-server - 使用聚合函数的 SQL 更新查询

database - ERD图中使用的继承符号是什么?

python - 加密将捆绑在 pyexe 文件中的 Sqlite 数据库文件

sql - 根据另一个表中的列名从一个表中选择列

sql - 在运行时显示 SQL Server 查询结果的数据类型和列大小

sql - 消息 8115,级别 16,状态 2,第 2 行算术溢出错误将表达式转换为数据类型 int

mysql - cmd 和 workbench mysql 之间查询的性能差异

sql-server-2008 - 使用 SQL Server 2008 运行 Access 2010 时出现运行时错误 '-2147024703 (800700c1)'

python - 从 SQL 数据库读取二进制数据(图像数据类型)并对其进行扩充,Matlab 与 Python