如何在sql server中的存储过程中使用外键

时间:2014-04-23 13:00:29

标签: sql sql-server stored-procedures

我有2桌艺术和艺术家。我编写了艺术存储过程,其中artistId是外键。在表格中插入数据的程序如下:

create procedure spInsertArts(
     @artsId int out,
     @name varchar(50),
     @category varchar(50),
     @artistId int
     )
     as
          begin
        select @artistId=SCOPE_IDENTITY()
            if exists(select artistId from artist)
              insert into arts(name,category,artistId) values(@name,@category,@artistId)
           end

当我执行它时,它会给出错误:

  

过程或函数'spInsertArts'需要参数`@artistId',它不是提供的。

我想将artistId设置为艺术家表中的artistId的最新值。

2 个答案:

答案 0 :(得分:1)

如果artistId始终是artist表中artistId的最新值,为什么还需要它作为参数?

你可以将它声明为这样的局部变量:

DECLARE @artistId INT
SET @artistId = ...

并相应地获得最新的artistId

答案 1 :(得分:0)

如果参数是可选的,则需要提供默认值:

create procedure spInsertArts(
     @artsId int out,
     @name varchar(50),
     @category varchar(50),
     @artistId int = null
     )

但是,如果你只是覆盖这个值,为什么它甚至是一个参数呢?

此外,我不确定最新的" ID属于这里。如果呼叫者正在插入艺术家,然后转身并插入艺术,则让呼叫者提供artistId。否则,您可以在插入艺术家后立即插入艺术(并在同一个连接上)。