在我的应用程序中,用户将插入一本书。例如,someBook将插入3个副本。 Table1.BookID = 1,Table1.Copy = 3,然后在另一个表中,这3本书将拥有其主键,因此它将是Table2.AccessionID = 1,2,3 Table2.BookID = 1,1,1。
这就是我目前正在做的事情,但正如Aaron Bertrand所说的那样糟糕。
int BookTitlesID;
public void addBookTitle()
{
int copy = int.Parse(textBox2.Text);
try
{
using (SqlConnection myDatabaseConnection = new SqlConnection(myConnectionString.ConnectionString))
{
myDatabaseConnection.Open();
using (SqlCommand mySqlCommand1 = new SqlCommand("INSERT INTO BookTitles(BookTitle, Copies) Values(@BookTitle, @Copies)", myDatabaseConnection))
{
mySqlCommand1.Parameters.AddWithValue("@BookTitle", BookTitletextBox.Text);
mySqlCommand1.Parameters.AddWithValue("@Copies", copy);
mySqlCommand1.ExecuteNonQuery();
}
}
}
catch (Exception Ex)
{
MessageBox.Show(Ex.Message, "Exception");
}
}
public void addBook()
{
int copy = int.Parse(textBox2.Text);
try
{
for (int x = 0; x < copy; x++)
{
using (SqlConnection myDatabaseConnection = new SqlConnection(myConnectionString.ConnectionString))
{
myDatabaseConnection.Open();
using (SqlCommand mySqlCommand1 = new SqlCommand("INSERT INTO book(BookTitleID) Values(@BookTitleID)", myDatabaseConnection))
{
mySqlCommand1.Parameters.AddWithValue("@BookTitleID", BookTitlesID);
mySqlCommand1.ExecuteNonQuery();
}
}
}
}
catch (Exception Ex)
{
MessageBox.Show(Ex.Message, "Exception");
}
}
private void Form_Load(object sender, EventArgs e)
{
using (SqlConnection myDatabaseConnection = new SqlConnection(myConnectionString.ConnectionString))
{
myDatabaseConnection.Open();
using (SqlCommand mySqlCommand1 = new SqlCommand("SELECT TOP 1 BookTitleID + 1 FROM BookTitles ORDER BY BookTitleID DESC", myDatabaseConnection))
{
string x = mySqlCommand1.ExecuteScalar().ToString();
BookTitlesID = Convert.ToInt32(x);
}
}
}
private void button1_Click(object sender, EventArgs e)
{
addBookTitle();
addBook();
}
答案 0 :(得分:5)
简化。最值得注意的是,as discussed in your other, related question,出去看看当前MAX
的内容绝对没有安全性,加1,并假设这将是下一个生成的身份值。如果在插入后检索它,则只能依赖该数字,最可靠的方法是使用SCOPE_IDENTITY()
(或者,对于多行{{1 },INSERT
子句。
OUTPUT
现在你可以真正简化你的C#代码(我不是C#代码,所以这是否是最好的方法,或者它是否会编译甚至超出我,但希望你可以自己解决这个问题。) / p>
CREATE PROCEDURE dbo.InsertBook
@BookTitle NVARCHAR(256),
@Copies INT
AS
BEGIN
SET NOCOUNT ON;
DECLARE @BookTitleID INT;
INSERT dbo.BookTitles(BookTitle, Copies) SELECT @BookTitle, @Copies;
SELECT @BookTitleID = SCOPE_IDENTITY();
INSERT dbo.Books(BookTitleID) SELECT @BookTitleID
FROM (SELECT TOP (@Copies) rn = ROW_NUMBER() OVER (ORDER BY [object_id])
FROM sys.all_objects ORDER BY [object_id]) AS y;
END
GO