来自JOIN的INSERT插入空值

时间:2012-05-01 09:42:26

标签: sql sql-server sql-server-2008 tsql

需要将3个表中的值插入另一个名为myTable的表中。 myTable中的必填字段是:

[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 pst.id_student=@id_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 sbj.id_subjects=@id_subjects)

1 个答案:

答案 0 :(得分: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 pst.id_student=@id_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 sbj.id_subjects=@id_subjects

GO