我使用Sql server 2008来存储我的数据,表结构是这样的
index float not null,
type int not null,
value int not null,
并且(索引,类型)是唯一的。没有两个数据具有相同的索引和相同的类型。
所以当我向表中插入数据时,我必须检查(索引,类型)对是否已经在表中,如果存在我使用更新语句,否则我直接插入它。但我认为这是不是一种有效的方法,因为:
大部分数据的索引类型对在表中是不存在的,所以选择操作是浪费,尤其是表很大。
当我使用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/