在SQL中使用IF条件计数

时间:2016-06-15 09:17:55

标签: sql sql-server sql-server-2008 sql-server-2005 sql-server-2008-r2

我将如何添加IF condition,如果单个学生已插入五个科目数据,那么我想将其限制为六个数据....正如我在下面的查询中所做的那样但我不能添加IF

SELECT Count(Student_ID) as 'StudentCount' 
FROM tbCourseSemOne
where Student_ID=1 
Having Count(Student_ID) < 6 and Count(Student_ID) > 0;

6 个答案:

答案 0 :(得分:1)

如果我理解正确,您希望防止表格中每名学生插入超过5个科目。

通常使用语句后触发器来完成。这种触发器不会在每行之后触发,而是仅在完成的命令之后触发。然后,您可以计算条目并在有太多时引发错误。

但是,据我所知,SQL Server不提供语句后触发器。所以我认为这在SQL Server 中是不可能的。 (当然,我可能错了。)

答案 1 :(得分:0)

我认为您要搜索的是如果不是EXISTS ,如果您的查询返回多行,则返回FALSE

If NOT Exist(Your Query)
Begin
  //Your insert query
End

<强>更新

IF Exists (SELECT 1  FROM CourseSemOne where Student_ID=1 Having Count(Student_ID) > 5)
BEGIN
    Print 'Your Error Message'
END

答案 2 :(得分:0)

Response.Cookie.Add

其中Student_ID = 1具有计数(Student_ID)&lt; 6和Count(Student_ID)&gt; 0) if(@Counter&lt; 6) 打印&#39;对不起!您不能为单个stduent添加超过五个主题数据&#39; 其他 打印&#39;插入代码&#39; 通过Student_ID从CourseSemOne订单中选择*;

答案 3 :(得分:0)

Declare @Counter int 
Set @Counter=(SELECT Count(Student_ID) as 'StudentCount' FROM CourseSemOne 
              where Student_ID=1 Having Count(Student_ID) < 6 and Count(Student_ID) > 0)
if(@Counter <6)
print'Sorry! You cannot add more than five subject data for a single stduent'
else
print'Insert Code'

答案 4 :(得分:0)

Declare @Counter int 
Set @Counter=(SELECT isnull(Count(Student_ID),0) as 'StudentCount' FROM     CourseSemOne  where Student_ID=1 )
if(@Counter >5)
print'Sorry! You cannot add more than five subject data for a   single         stduent'
else

print'Insert Code'

答案 5 :(得分:0)

               Solved myself :)
               string sql = "SELECT Count(Student_ID) FROM CourseSemOne where Student_ID='"+Student_ID+"' Group by Student_ID ";
                SqlConnection con = new SqlConnection(@"Data Source=LOCALHOST\SQLEXPRESS;Initial Catalog=CS_DB;Integrated Security=True");
                con.Open();
                SqlCommand cmd = new SqlCommand(sql, con);
                int count = Convert.ToInt32(cmd.ExecuteScalar());
                con.Close();

                if (count <5 && count >=0)
                {
                    obj.insertSemCourseOne(Student_ID, Course_Code, Course_Title, Total_Marks, Obtain_Marks, Grade, Value, Cr_Hours, Grade_Point, GPA, CGPA);
                   // DatabaseConnnectionClass.UserMessage("Added");
                    MessageBox.Show("Added Subject");
                    Dataloaddd();
                }
                else
                {

                    MessageBox.Show("Sorry!For this Student ID = "+Student_ID+" You cannot add more than 5 data.");
                }