简体   繁体   English

如何插入外键值

[英]How to insert foreign key value

I have two tables artist and arts . 我有两张桌子artistarts artistId is the primary key in the artist table and it is the foreign key in arts table. artistIdartist表中的主键,也是arts表中的外键。 I am using a stored procedure to insert data. 我正在使用存储过程来插入数据。 First artist log in and then art info page is displayed where artist insert art info. 首先登录艺术家,然后显示艺术家信息页面,其中插入艺术家信息。 I want that artist id to get inserted in arts table also when he inserts art info. 我希望插入艺术家信息时也将其插入arts表中。

I tried this as: 我尝试这样做:

Stored procedure: 存储过程:

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

asp.net code: asp.net代码:

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

It is not working. 它不起作用。

I am new to stored procedure. 我是存储过程的新手。 Please help me to get the foreign key value. 请帮助我获取外键值。 Or is there any other way? 还是还有其他方法?

When you do this: 执行此操作时:

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

Shouldn't you be checking against who is logged in? 您不应该检查谁在登录吗? Something like: 就像是:

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

Aren't you trying to see if they exist before you insert art for them? 在为它们插入艺术品之前,您是否要尝试查看它们是否存在? Is that the issue? 那是问题吗? But like the comments above say, it is difficult to guess at the problem without more info. 但是就像上面的评论所说,没有更多信息就很难猜测问题所在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM