1

我有以下存储过程,我这里有两个表,电影和导演。当创建或添加新电影时,两者都需要更新。您如何处理存储过程中的 FK?在这种情况下,FK 是director_id。它是一个主键,Director但是一个 FKMovie 我需要像这样指定它两次吗?我收到冲突错误

CREATE PROCEDURE Book_Book_Creation
    @Book_id_arg DECIMAL(12),    
    @author_id_arg DECIMAL(12),    
    @type_id_arg DECIMAL(12),     
    @title_arg VARCHAR(64),      -
    @copyright_arg DECIMAL(4),   
    @dauthor_id_2_arg DECIMAL(12),    
    @author_fname_arg VARCHAR (64), 
    @author_lname_arg VARCHAR (64)  
AS
BEGIN 
    INSERT INTO Book(Book_id, author_id,genre_id, title, copyright)
    VALUES (@author_arg, @author_id_arg,  @type_id_arg, @title_arg, @copyright_arg);
    INSERT INTO Author(author_id, author_fname, author_lname)
    VALUES (@director_id_2_arg, @director_fname_arg, @director_lname_arg)
END;

EXECUTE Book_Book_Creation 32,32,1,'Tempting',2013,32,'Taylor','Mendez';
4

2 回答 2

6

基本上,您只需要这样做:

  • 先插入Director表格
  • 从该表中获取新插入的 ID(假设该Director_Id列是您的主键并且类型为INT IDENTITY
  • Movie然后使用该新 ID插入表中

像这样的东西:

DECLARE @NewDirectorID INT

INSERT INTO Director (Director_id, Director_fname, director_lname)
VALUES (@director_id_2_arg, @director_fname_arg, @director_lname_arg)

SELECT @NewDirectorID = SCOPE_IDENTITY()

INSERT INTO Movie (Movie_id, director_id,genre_id, title, copyright)
VALUES (@movie_id_arg, @NewDirectorID,  @genre_id_arg, @title_arg, @copyright_arg);

我不明白您为什么要将导演的 ID 作为参数传递 - 两次!

于 2013-04-23T05:20:51.083 回答
0

试试这个——

ALTER PROCEDURE dbo.Movie_Movie_Creation12

    @movie_id_arg DECIMAL(12),  
    @director_id_arg DECIMAL(12),
    @genre_id_arg DECIMAL(12), 
    @title_arg VARCHAR(64),
    @copyright_arg DECIMAL(4),  
    @director_fname_arg VARCHAR (64), 
    @director_lname_arg VARCHAR (64) 

AS BEGIN 

    INSERT INTO dbo.Director (Director_id, Director_fname, director_lname)
    SELECT @director_id_arg, @director_fname_arg, @director_lname_arg

    INSERT INTO dbo.Movie (Movie_id, director_id,genre_id, title, copyright)
    SELECT @movie_id_arg, @director_id_arg,  @genre_id_arg, @title_arg, @copyright_arg

END

EXECUTE dbo.Movie_Movie_Creation12  
            @movie_id_arg = 32 
        ,   @director_id_arg = 32
        ,   @genre_id_arg = 1
        ,   @title_arg = 'Argo'
        ,   @copyright_arg = 2012
        ,   @director_fname_arg = 'Ben'
        ,   @director_lname_arg = 'Affleck'
于 2013-04-23T05:29:07.470 回答