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();
3
  • just to be sure, do all of the values for User_Receiver exist in the Users table? Commented Dec 25, 2012 at 2:07
  • 2
    Suggest you to use sql profiler to see whether insert command is executed. If not, try to create new instanst for dataCommand in loop Commented Dec 25, 2012 at 2:08
  • 1
    When you .Add the parameter for @User_Receiver try supplying the maximum length as the third argument. Commented Dec 25, 2012 at 2:50

2 Answers 2

1

I discovered that my Split() function was adding a space to the end of each User_Receiver. This caused only the first INSERT function to work and the subsequent ones to not go thru. The INSERT-SELECT function was set up correctly but the data I fed into it wasn't correct. Thank you for the help guys.

Sign up to request clarification or add additional context in comments.

Comments

0

Seems like you should use bulkinserter, it will be quicker and is made for bulk inserting :)

1 Comment

I tried Initializing he data command inside of the loop, but no effect. I also explicitly stated the maximum length in the AddWithValue() functions; no effect. I would like to try bulkinserter, but I know that it's used for transactions where there are 1000's of rows whereas I only have about 10. Shouldn't what I have work? Is this a bug?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.