如何,我會添加IF condition
,如果一個學生有已插入然後五點科的數據我想限制它的六個數據....正如我已經這樣做了下面的查詢,但我不能用這個添加IF
。計數與SQL IF條件
SELECT Count(Student_ID) as 'StudentCount'
FROM tbCourseSemOne
where Student_ID=1
Having Count(Student_ID) < 6 and Count(Student_ID) > 0;
如何,我會添加IF condition
,如果一個學生有已插入然後五點科的數據我想限制它的六個數據....正如我已經這樣做了下面的查詢,但我不能用這個添加IF
。計數與SQL IF條件
SELECT Count(Student_ID) as 'StudentCount'
FROM tbCourseSemOne
where Student_ID=1
Having Count(Student_ID) < 6 and Count(Student_ID) > 0;
如果我理解正確,您想防止每個學生在表格中插入超過5個科目。
這通常被用做後聲明觸發。這種觸發器不會在每行之後觸發,而只會在完成的命令之後觸發。然後,您可以對條目進行計數,並在出現太多時提出錯誤。
不過,據我所知,SQL Server不提供售後服務聲明觸發器。所以我認爲這是不可能在SQL Server。 (我可能是錯的,不過,當然。)
是的先生你明白了@Thorsten Kettner –
你應該怎麼解決它?@Thorsten Kettner –
如上所述,我想不出來以任何方式在SQL Server中完全自動執行此操作。也許你可以用一個約束'counter(1,2,3,4,5)'和'(student_id,counter)'上的一個唯一鍵來爲表添加一個'counter'列。因此,你只能爲每個學生插入5個科目,但你必須在插入時處理找到所需的「計數器」。 –
我認爲你正在尋找爲IF NOT 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
nop先生我沒有這個意思@krish –
Declare @Counter int Set @ Counter =(SELECT Count(Student_ID)as'StudentCount'FROM CourseSemOne where Student_ID = 1 Having Count(Student_ID) (@Counter <6) print'Sorry!您無法爲單個stduent添加超過五個主題數據' 其他 print'Insert代碼' –
一個月後我解決了這個邏輯我自我 –
Declare @Counter int
Set @Counter=(SELECT Count(Student_ID) as 'StudentCount' FROM CourseSemOne
其中student_id數據= 1具有計數(student_id數據)< 6和計數(student_id數據)> 0) 如果(@Counter < 6) print'Sorry!你不能爲一個單一的stduent添加五個以上的實驗數據「 其他 print'Insert代碼」 SELECT * FROM由student_id數據CourseSemOne秩序;
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'
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'
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.");
}
添加簡單的輸入輸出爲更好地瞭解 –
這是什麼意思:如果一個學生有** 5 **實驗數據已經被插入的話,我想限制它**六個**數據? –
是否要排除超過5個條目的學生,或者每個學生只包含5個條目?一些示例數據和輸入/輸出將是有益的.. – StevieG