2012-05-01 49 views
1

需要從3個表中插入值到另一個表稱爲myTable。 myTable中的必填字段爲:插入從JOIN插入空值

[Id_student] int, 
[id_subjects] int 
[degrees] float 
[st_Name] nvarchar(30) 
[Id_Class] int 
[Id_Group] int 
[Class] nvarchar(15) 
[group] nvarchar(15))` .. 

我在下面創建了存儲過程。但查看錶後,我發現只有傳遞的參數才被保存!即@Id_student , @id_subjects , @degrees。任何人都可以解釋這段代碼有什麼問題嗎?

CREATE storedprocedure mySp_myTable_insert 
     @Id_student int, 
     @id_subjects int, 
     @degrees  int 
as 

DECLARE @st_Name nvarchar(30) 
SELECT @st_Name = pst.st_Name FROM dbo.sudents AS pst where [email protected]_student ; 

INSERT [myTable] 
    (
     [Id_student], 
     [id_subjects], 
     [degrees], 
     [st_Name], 
     [Id_Class], 
     [Id_Group], 
     [Class], 
     [group] 
    ) 

    (select 
     @Id_student, 
     @id_subjects, 
     @degrees, 
     @st_Name 
     ,tc.Id_Class 
     ,tg.Id_Group 
     ,tc.Class 
     ,tg.group 
    from dbo.subjects sbj 
    inner join tGroup tg 
    inner join tClass tc 
     on tc.Id_Class=tg.Id_Class 
     on sbj.Id_Group =tg.Id_Group 
    where [email protected]_subjects) 
+1

@Siva,你應該張貼此作爲一個答案, – Habib

+2

@Siva'INTO'根據T-SQL規格可選:http://msdn.microsoft.com /en-us/library/ms174335.aspx – GolfWolf

+0

@Siva,謝謝,但[Into]是可以在INSERT和目標表之間使用的可選關鍵字。請參閱[link](http://msdn.microsoft.com/ en-us/library/aa933206(v = sql.80).aspx) – Salahaldin

回答

3

我想你應該放棄括號圍繞SELECT聲明和修復join的順序 - on關鍵字/條款。

試試這個版本:

CREATE storedprocedure mySp_myTable_insert 
     @Id_student int, 
     @id_subjects int, 
     @degrees  int 
as 

DECLARE @st_Name nvarchar(30) 
SELECT @st_Name = pst.st_Name FROM dbo.sudents AS pst where [email protected]_student ; 

INSERT [myTable] 
    (
     [Id_student], 
     [id_subjects], 
     [degrees], 
     [st_Name], 
     [Id_Class], 
     [Id_Group], 
     [Class], 
     [group] 
    ) 
select 
    @Id_student, 
    @id_subjects, 
    @degrees, 
    @st_Name 
    ,tc.Id_Class 
    ,tg.Id_Group 
    ,tc.Class 
    ,tg.group 
from dbo.subjects sbj 
inner join tGroup tg on sbj.Id_Group =tg.Id_Group 
inner join tClass tc on tc.Id_Class=tg.Id_Class 
where [email protected]_subjects 

GO 
+0

我試過了,它不會變得與衆不同! – Salahaldin

+0

你可以試試只運行'select'嗎?它是否返回有效數據? – GolfWolf

+0

yes確實..但是字段([st_Name],[Id_Class],[Id_Group],Class,[group])爲空。 – Salahaldin