2013-03-23 59 views
1

我正在使用SQL Server 2008。請看下面的表格:在SQL Server 2008中將默認值插入MANT-TO-MANY關係的腳本

學生

╔════╦═══════════╦══════════╗ 
║ ID ║ FIRSTNAME ║ LASTNAME ║ 
╠════╬═══════════╬══════════╣ 
║ 1 ║ joe  ║ Smith ║ 
║ 2 ║ frank  ║ Smith ║ 
║ 3 ║ Scott  ║ Smith ║ 
╚════╩═══════════╩══════════╝ 

課程

╔════╦═════════╦════════════════╗ 
║ ID ║ NAME ║ DESCRIPTION ║ 
╠════╬═════════╬════════════════╣ 
║ 1 ║ Physics ║ PHYSICS COURSE ║ 
║ 2 ║ MATH ║ COURSE   ║ 
╚════╩═════════╩════════════════╝ 

STUDENT_COURSE

╔════════════╦═══════════╦═══════╗ 
║ STUDENT_ID ║ COURSE_ID ║ GRADE ║ 
╠════════════╬═══════════╬═══════╣ 
║   1 ║   1 ║  9 ║ 
║   2 ║   1 ║  8 ║ 
║   3 ║   1 ║  6 ║ 
╚════════════╩═══════════╩═══════╝ 

我需要爲MATH課程的所有用戶插入默認等級10,如果該用戶不存在此等級。

我不熟悉Microsoft SQL Server和T-SQL。你能幫我解決這個問題嗎?

+1

微軟的產品被稱爲** SQL Server的**,其查詢語言「方言」是** T-SQL **(Transact-SQL) –

回答

3
INSERT INTO STUDENT_COURSE (Student_ID, course_ID, grade) 
SELECT a.ID as StudentID, b.ID as Course_ID, 10 AS grade 
FROM Student a 
     CROSS JOIN Course b 
     LEFT JOIN 
     (
      SELECT d.* 
      FROM STUDENT_COURSE d 
        INNER JOIN Course e 
         ON d.Course_ID = e.ID 
      WHERE e.Name = 'Math' 
     ) c ON a.ID = c.student_ID AND 
       b.ID = c.course_ID 
WHERE c.student_ID IS NULL AND 
     b.Name = 'Math' 

輸出STUDENT_COURSE

MySQL> SELECT * FROM STUDENT_COURSE 

╔════════════╦═══════════╦═══════╗ 
║ STUDENT_ID ║ COURSE_ID ║ GRADE ║ 
╠════════════╬═══════════╬═══════╣ 
║   1 ║   1 ║  9 ║ 
║   2 ║   1 ║  8 ║ 
║   3 ║   1 ║  6 ║ 
║   1 ║   2 ║ 10 ║ 
║   2 ║   2 ║ 10 ║ 
║   3 ║   2 ║ 10 ║ 
╚════════════╩═══════════╩═══════╝ 
+0

你救了我:) –

+0

很高興它幫助':D' –