2012-08-25 27 views
0

这是学生图书馆项目的一部分。插入语句不会在数据库中插入多于一行

有2个表:alertsborrows

borrows包含studentID,bookIDdate of borrowing

alerts指示哪些学生过期多少本书。

该代码应该为每个过期的学生插入一行,并计算过期的书籍数量。

Est_Return_Date = return_date + 30 

insert into dbo.Alert (studentID, AlertCount) 
    values ((select distinct (studentID)from dbo.Borrows 
     where Est_Return_Date < GETDATE() 
     and return_date is null), 
     (select count(studentID) from dbo.Borrows 
     where Est_Return_Date < GETDATE() 
     and return_date is null)) 
+1

计数将始终返回一个值。而另一个选择可能还会返回一个值,那就是你的问题。你有错误的查询 –

+0

在查询中使用'GetDate()'是追逐一个移动的目标,影响性能,并可能产生好奇的结果。随着日期的变化。在变量中捕获当前日期/时间几乎总是一个更好的主意,然后根据需要使用该值。在存储过程中,这在多个语句中更重要。多次使用'GetDate()'的最常见原因是捕获长时间运行操作的开始和结束时间。 – HABO

回答

2

你将要使用GROUP BY,而不是子查询,你想要的是每studentId的结果,所以GROUP BY这一点,COUNT与警报行;

INSERT INTO dbo.Alert (studentID, AlertCount) 
SELECT studentID,COUNT(*) 
FROM dbo.Borrows 
WHERE Est_Return_Date < GETDATE() 
AND return_date is NULL 
GROUP BY studentID; 

演示here

1

试试这个

insert into dbo.Alert (studentID, AlertCount) 
select studentId, count(*) as AlertCount from dbo.Borrows where Est_Return_Date < GETDATE() 
     and return_date is null group by studentId 

考虑你想要做什么,你的查询将始终插入值1 - 计数被返回的学生总数计数,并可能是你的另一个选择也返回一个只有价值。此查询将按学生分组,并计算其他表的总书数,逾期时间

通过here阅读有关组的内容。如果它是MySQL也可以。 另一个页面,其中一个例子,是here