1

I have a comma delimited textbox and a loop which parses it out and loops to create a series of SQL INSERT statements. However, only the first SQL INSERT statement in [Message_Bridge] is working. The foreach statement is working fine the first time through, but subsequent iteration do not INSERT. No errors are thrown.

dataCommand.CommandText = "INSERT INTO [Messages]([Subject], [Body], [Date_Time], [Originator], [Canceled], [Message_Index]) VALUES(@Subject, @Body, GETDATE(), @Originator, 0, 0); SELECT SCOPE_IDENTITY();";

dataCommand.Parameters.Clear();
dataCommand.Parameters.AddWithValue("@Subject", ComposeSubjectTexbox.Text);
dataCommand.Parameters.AddWithValue("@Body", ComposeBodyTexbox.Text);
dataCommand.Parameters.AddWithValue("@Originator", 506);
var Message_ID = dataCommand.ExecuteScalar();

string[] Recipients = ComposeToTextBox.Text.Split(',');

dataCommand.CommandText = "INSERT INTO [Message_Bridge]([Message_ID], [User_ID]) SELECT TOP 1 @Message_ID, [User_ID] FROM [Users] WHERE [User_Name] = @User_Receiver; ";
dataCommand.Parameters.Clear();
dataCommand.Parameters.AddWithValue("@Message_ID", Message_ID);
dataCommand.Parameters.Add("@User_Receiver", SqlDbType.NVarChar);

foreach (string User_Receiver in Recipients)
{
    dataCommand.Parameters["@User_Receiver"].Value = User_Receiver;
    dataCommand.ExecuteNonQuery();
}

myConnection.Close();
4

2 回答 2

1

我发现我的 Split() 函数在每个 User_Receiver 的末尾添加了一个空格。这仅导致第一个 INSERT 功能起作用,而随后的功能无法通过。INSERT-SELECT 函数设置正确,但我输入的数据不正确。谢谢你们的帮助。

于 2012-12-26T20:14:20.573 回答
0

似乎您应该使用bulkinserter,它会更快并且用于批量插入:)

于 2012-12-25T03:18:52.137 回答