我有两张桌子,一张是
peson contains(personid Identity, firstname,Lastname,PlaceOfBirth,Gender)
和另一个
Education contains (Eduid identity, egreename,boardUniver,yearOfPassing,obtainedMarks, personid)
现在我的问题是每个人都有1个以上的学位,但有些人有1个或2个学位,所以我怎么能跳过插入查询呢?
第一张表
Create table person(personid int Identity(1,1) primary key, firstname nvarchar(40), Lastname nvarchar(40), PlaceOfBirth nvarchar(40), Gender nvarchar(10))
第二张表
create table Education(Eduid int identity(1,1) primary key, Degreename nvarchar(40), boardUniver nvarchar(40), yearOfPassing nvarchar(40), obtainedMarks numeric(10,2), personid int,
constraint fk_eduPerson foreign key (personid) references person(personid))
存储信息的程序
Create procedure EmpDetails
(
@Firstname nvarchar(40), @Lastname nvarchar(40), @PlaceOfBirth nvarchar(40), @Gender nvarchar(8),
@Degreename0 int, @boardUniver0 nvarchar(40), @yearOfPassing0 nvarchar(20), @obtainedMarks0 int,
@Degreename1 int, @boardUniver1 nvarchar(40), @yearOfPassing1 nvarchar(20), @obtainedMarks1 int,
@Degreename2 int, @boardUniver2 nvarchar(40), @yearOfPassing2 nvarchar(20), @obtainedMarks2 int,
)
AS BEGIN
declare @personid int
INSERT INTO person(firstname,Lastname,PlaceOfBirth,Gender) values(@firstname,@Lastname,@PlaceOfBirth,@Gender)
SELECT @personid=@@IDENTITY
if(@Degreename0 !=NULL)
BEGIN
INSERT INTO Education(Degreename,boardUniver,yearOfPassing,obtainedMarks, personid) values (@Degreename0,@boardUniver0,@yearOfPassing0,@obtainedMarks0, @personid)
END
IF(@Degreename1 !=null)
BEGIN
INSERT INTO Education(Degreename,boardUniver,yearOfPassing,obtainedMarks, personid) values (@Degreename1,@boardUniver1,@yearOfPassing1,@obtainedMarks1, @personid)
END
IF(@Degreename2!=null)
BEGIN
INSERT INTO Education(Degreename,boardUniver,yearOfPassing,obtainedMarks, personid) values (@Degreename2,@boardUniver2,@yearOfPassing2,@obtainedMarks2,@personid)
END
END
这不起作用..这会将所有行都插入空..有没有其他解决方案可以做到这一点? 如果有其他的话请提出建议..谢谢
答案 0 :(得分:1)
尝试使用IS NOT NULL
代替!= NULL
。在大多数关系数据库中,如果任一输入为NULL
,则比较运算符返回false,即使它们都是INSERT
。 Here是一个证明行为的SQL小提琴。
(对不起。那个SQL小提琴确实有效。)
不可否认,这很令人困惑,因为这个事实应该意味着你的所有{{1}}都被跳过了。我在这里看不到任何会插入空行的内容。
答案 1 :(得分:0)
试试这个 -
Create procedure EmpDetails
(
...
)
AS BEGIN
DECLARE @personid INT
INSERT INTO Person (firstname, Lastname, PlaceOfBirth, Gender)
SELECT @firstname, @Lastname, @PlaceOfBirth, @Gender
SELECT @personid = SCOPE_IDENTITY()
INSERT INTO Education (Degreename, boardUniver, yearOfPassing, obtainedMarks, PersonID)
SELECT a = @Degreename0, b = @boardUniver0, c = @yearOfPassing0, d = @obtainedMarks0, e = @personid
WHERE @Degreename0 IS NOT NULL
UNION ALL
SELECT @Degreename1, @boardUniver1, @yearOfPassing1, @obtainedMarks1, @personid
WHERE @Degreename1 IS NOT NULL
UNION ALL
SELECT @Degreename2, @boardUniver2, @yearOfPassing2, @obtainedMarks2, @personid
WHERE @Degreename2 IS NOT NULL
END