存储过程中的外键约束 - SQL Server

时间:2013-04-23 05:10:42

标签: sql-server tsql

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

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';

2 个答案:

答案 0 :(得分:5)

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

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

这样的事情:

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作为参数传递 - 两次!

答案 1 :(得分: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'