如何插入外键值

时间:2014-04-28 14:53:37

标签: c# asp.net sql-server

我有两张表artistartsartistIdartist表中的主键,它是arts表中的外键。我正在使用存储过程来插入数据。首先登录艺术家,然后显示艺术信息页面,其中艺术家插入艺术信息。我想在插入艺术信息时将艺术家ID插入艺术表中。

我试过这个:

存储过程:

if exists(select artistId from artist)
    insert into arts(name, description, artistId) 
    values(@name, @description, @artistId)

asp.net代码:

cmd.Parameters.AddWithValue("@name",txtname.Text);
cmd.Parameters.AddWithValue("@category",ddlcategory.SelectedValue);

它不起作用。

我是存储过程的新手。请帮我获取外键值。或者还有其他方法吗?

1 个答案:

答案 0 :(得分:0)

执行此操作时:

if exists(select artistId from artist)
    insert into arts(name, description, artistId) 
    values(@name, @description, @artistId)

您是否应该检查谁登录?类似的东西:

if exists(select 1 from artist where artistId = @artistId)
    insert into arts(name, description, artistId) 
    values(@name, @description, @artistId)

在为他们插入艺术品之前,你不是想看看它们是否存在吗?这是问题吗?但就像上面的评论所说的那样,如果没有更多的信息,就很难猜到这个问题。

相关问题