存储过程不插入所有行

时间:2015-06-11 23:05:04

标签: sql csv stored-procedures insert-into

对于学校项目,我们需要制作一个Web应用程序。其中一个功能应该是您可以导入.csv文件,并且所有行都应该插入到右表中,除非(在这种情况下)歌曲或艺术家已经存在。 .csv文件由2000行组成,应始终将其插入到不同的表中。代码运行,但实际只插入了137行。 这是我的代码:

BEGIN
SET NOCOUNT ON;

IF EXISTS(SELECT naam FROM Artiest WHERE naam = @artiest)
PRINT NULL;
ELSE
INSERT INTO Artiest(naam) VALUES (@artiest);
END
BEGIN
SET NOCOUNT ON;

IF EXISTS(SELECT titel FROM Song WHERE titel = @titel AND artiestid = (SELECT artiestid FROM Artiest WHERE naam = @artiest))
PRINT NULL;
ELSE
INSERT INTO Song(artiestid, titel, jaar) VALUES ((SELECT TOP(1) artiestid FROM Artiest WHERE naam = @artiest), @titel, @jaar);
END
BEGIN
SET NOCOUNT ON;

IF EXISTS (SELECT TOP(1) songid FROM Lijst WHERE songid = (SELECT TOP(1) songid FROM Song WHERE titel = @titel AND artiestid = (SELECT artiestid FROM Artiest WHERE naam = @artiest)))
AND EXISTS (SELECT TOP(1) top2000jaar FROM Lijst WHERE top2000jaar = @top2000jaar)
PRINT null;
ELSE
INSERT INTO Lijst (songid, top2000jaar, positie, uitzendDatum, van, tot) VALUES ((SELECT TOP(1) songid FROM Song WHERE titel = @titel AND artiestid = (SELECT artiestid FROM Artiest WHERE naam = @artiest)), @top2000jaar, @positie, @eindzenddatum, @van, @tot);
END

希望有人可以帮助我解决这个问题,因为在谈到SQL时我是个新手

1 个答案:

答案 0 :(得分:0)

我已经简化了sql以使其更具可读性,

BEGIN
    SET NOCOUNT ON;

    DECLARE @artiestID INT,
            @SongID INT

    SELECT @artiestID = artiestid FROM Artiest WHERE naam = @artiest

    IF @artiestID IS NULL
    BEGIN
        INSERT INTO Artiest(naam) VALUES (@artiest);
        SELECT @artiestID = @@IDENTITY
    END

    SELECT @SongID = songid FROM Song WHERE titel = @titel AND artiestid = @artiestID

    IF @SongID IS NULL
    BEGIN
        INSERT INTO Song(artiestid, titel, jaar) VALUES (@artiestID, @titel, @jaar);
        SELECT @SongID = @@IDENTITY
    END

    IF NOT EXISTS (SELECT 1 FROM Lijst WHERE songid = @SongID) OR NOT EXISTS (SELECT 1 top2000jaar FROM Lijst WHERE top2000jaar = @top2000jaar)
        INSERT INTO Lijst (songid, top2000jaar, positie, uitzendDatum, van, tot) VALUES (@SongID, @top2000jaar, @positie, @eindzenddatum, @van, @tot);
END

验证您的数据以确定目标表记录数量较少的原因。