insert into tableB
select ID from tableA a left join tableB b on a.ID=b.ID where b.ID is null我用这种办法插入数据,为什么会出现重复的插入,插入时间相同或者相距十几毫秒这是个web项目,每次点击按钮都会自来来找表A中的ID,一旦表B没有,就插入到表B,为了防止出现重复,我也懒得做判断,就这样写了sql,难道我的sql有bug?
select ID from tableA a left join tableB b on a.ID=b.ID where b.ID is null我用这种办法插入数据,为什么会出现重复的插入,插入时间相同或者相距十几毫秒这是个web项目,每次点击按钮都会自来来找表A中的ID,一旦表B没有,就插入到表B,为了防止出现重复,我也懒得做判断,就这样写了sql,难道我的sql有bug?
解决方案 »
- 连c#接数据库的问题,求大神指教!
- datarow 显示不可访问,因为它受保护级别限制,是什么意思
- c#中有没有调节时间的控件?
- 大家有没有象Windows地址栏这样的Combox源码。
- 我用sqlCommand1.ExecuteReader()函数,得到的结果集,如何绑定到dataGridView?
- DataTable的返回值用null好吗?怎样的效率比较高
- c#中datagrid的doubleclick事件中怎样获得mouse在datagrid中选定的row?
- !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!为何没人理,特送高分,见者有分!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
- 英雄帖!!!!!!!!!!!!!!!!!!!
- 奇怪的问题(自动重启)
- 帮忙看一下这个软件功能是用什么控件实现的??
- C# 委托
针对这种类型的SQL可以考虑在程序一级加锁,只允许一个并发
比如设TableA中有一个x不存在于TableB中,有两个任务A,B同时执行,A能select到x,B也可能select到x,所以A,B都有可能将x插入到TableB中。
当然,你也可以建立unique类型的索引,执行失败的会报异常。只是我认为,这条SQL最好是限制并发。
我认为我用insert into table select……的办法是把查询和插入都在数据库服务器端执行的
我用程序是干预不到的,所以才这样使用,防止重复插入如果我用程序先select 数据到object ,再insert object到数据库,这样操作,我觉得可以从程序这里控制可以给我个简单的例子说一下从程序这里限制并发的方法吗?也许可以帮助我理解你的意思
from tableA a where not exists(select * from tableB b where a.ID=b.ID)
using System.Threading;
using System.Reflection;namespace showjim.sys.threading
{
public class singleCall
{
private Action Call;
private int IsCalling = 0;
private int IsNewCall = 0;
private readonly object CompleteLock;
public singleCall(Action call, bool isComplete)
{
Call = call;
if (isComplete) CompleteLock = new object();
}
public void call()
{
if (CompleteLock == null)
{
if (Interlocked.Exchange(ref IsCalling, 1) == 0)
{
try
{
Call();
}
catch (Exception error)
{
showjim.sys.exception.debug.writeDebug(MethodBase.GetCurrentMethod(), error);
}
finally { IsCalling = 0; }
}
}
else
{
Monitor.Enter(CompleteLock);
int isCalling = IsNewCall = IsCalling;
IsCalling = 1;
Monitor.Exit(CompleteLock);
if (isCalling == 0)
{
do
{
try
{
Call();
}
catch (Exception error)
{
showjim.sys.exception.debug.writeDebug(MethodBase.GetCurrentMethod(), error);
}
finally
{
Monitor.Enter(CompleteLock);
isCalling = IsCalling = IsNewCall;
IsNewCall = 0;
Monitor.Exit(CompleteLock);
}
}
while (isCalling != 0);
}
}
}
}
}初始化一个实例 class test
{
private static void DoSql()
{
string sql = "insert into tableB select ID from tableA where not exists(select ID from tableB where ID=tableA.ID)";
//..执行SQL
}
public static showjim.sys.threading.singleCall doSql
static test()
{
doSql = new showjim.sys.threading.singleCall(DoSql, true);
}
}外部调用
test.doSql.call();
等第一个执行完了,表B中就有了A的ID,再执行一次也不会插入数据了
怀疑是A表中有重复ID