I am using multiview index to insert the news details. In the first view the user can enter details of news which is then inserted into db on clicking the next button
the second view gives a user to add images of that news (only 3 images allowed) ,
what I am having problem is that the first view inserts data into the table dbo.newsdetail with a primary key
newsID , while the second view should add the respected images using that newsId of the news just added into newsimages table. I just dont know how to get the newsID of the details
which is added in the first view as news Id is working as a foreign key for the both the table. Any help or suggestions will be highly appreciated .
static public void insertNews(string newsDescription, string newsImage, string newsTitle)
{
SqlConnection conn = new SqlConnection(ConnectionString);
conn.Open();
SqlCommand insertNews = new SqlCommand("Insert INTO caravanNews(newsDescription, newsImage, newsTitle) VALUES ('" + newsDescription + "', '" + newsImage + "' , '" + newsTitle + "')",conn);
insertNews.ExecuteNonQuery();
conn.Close();
}
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
A separate SQL statement
SELECT SCOPE_IDENTITY()
Or the OUTPUT clause
INSERT MyTable (...= OUTPUT INSERTED.KeyCol VALUES (...) --Or SELECT ... FROM Another table)
Edit:
- change your insert statement to match mine
- change .ExecuteNonQuery() to blah = xxx.ExecuteScalar()
Method 2
As part of your INSERT statement (into the first News table), after it runs, execute
SELECT SCOPE_IDENTITY()
and return NewsId value to caller.
Ref.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0