Hello,
I am trying to save a list of multiple choices as rows with same ID in database once hit submit from my form, I created a store procedure to save data. Can you please help me on this?
Thank you.
Hello,
I am trying to save a list of multiple choices as rows with same ID in database once hit submit from my form, I created a store procedure to save data. Can you please help me on this?
Thank you.
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Emily FosterRank #3,495 · 415 reputationPosted Feb 25, 2025, 11:21 AM EST
Hello! It sounds like you're looking to save multiple choices as individual rows in a database table, all associated with the same ID. This can be a common requirement in many applications, especially when dealing with forms that capture multiple selections.
To achieve this, you can follow these general steps:
1. Form Submission:
When the user submits the form with the multiple choices selected, your backend (whether it be in a programming language like Python, PHP, Java, etc.) receives this data.
2. Database Interaction:
You mentioned using a stored procedure to save the data. In the stored procedure, you'll want to iterate through the list of choices and insert each choice as a separate row in the database table. Make sure you include the common ID that links all these choices together.
3. Stored Procedure Example (MySQL):
Here's a simplified example of how your stored procedure might look in MySQL to save multiple choices under the same ID:
DELIMITER // CREATE PROCEDURE SaveChoices(IN common_id INT, IN choices TEXT) BEGIN DECLARE i INT DEFAULT 1; DECLARE choice VARCHAR(255); WHILE i <= LENGTH(choices) DO SET choice = SUBSTRING_INDEX(SUBSTRING_INDEX(choices, ',', i), ',', -1); INSERT INTO choices_table (common_id, choice_column) VALUES (common_id, choice); SET i = i + 1; END WHILE; END // DELIMITER ;4. Calling the Stored Procedure:
From your backend code, you would then call this stored procedure, passing in the common ID and the list of choices (which could be formatted as a comma-separated string, for example).
5. Validation and Security:
Ensure that you validate and sanitize the user input to prevent any potential security risks like SQL injection.
By following these steps and adjusting them to fit the specifics of your application and database system, you should be able to save multiple choices as individual rows with the same ID successfully. If you encounter any specific issues or need further assistance with a particular database system or programming language, feel free to provide more details!
Jignesh KumarRank #91 · 22.9K reputationPosted Feb 25, 2025, 12:03 PM EST
Hello,
You can create store procedure as below,
CREATE PROCEDURE Usp_SaveMultipleChoices @MainID INT, @Choices NVARCHAR(MAX) AS BEGIN SET NOCOUNT ON; DECLARE @ChoiceTable TABLE (ChoiceID INT); -- Convert the comma-separated list into table format INSERT INTO @ChoiceTable (ChoiceID) SELECT value FROM STRING_SPLIT(@Choices, ','); -- Insert into your table INSERT INTO ChoicesTable (MainID, ChoiceID) SELECT @MainID, ChoiceID FROM @ChoiceTable; END;Sreenath KappoorRank #655 · 3.7K reputationPosted Feb 26, 2025, 12:12 AM EST
Hello
To avoid conversion errors, you can cast the value as INT. Also check if the value is numeric in where condition.
For example;
INSERT INTO @CHOICETABLE (CHOICEID) SELECT VALUE FROM STRING_SPLIT(@CHOICES, ',');
This query can be changed as
SELECT DISTINCT TRY_CAST(TRIM(value) AS INT)
FROM STRING_SPLIT(@Choices, ',')
WHERE ISNUMERIC(TRIM(value)) = 1
TRY_CAST - Trim spaces and convert to INT
ISNUMERIC - Only numeric values are processed
This will insert only numeric values.
Tuhin PaulRank #7 · 71.9K reputationPosted Feb 26, 2025, 5:24 AM EST
Part - 1
Let's assume you have:
A form with multiple checkboxes (e.g., user selections)
Need to store selections in a table with structure:
This procedure handles multiple choices using a comma-separated string:
CREATE PROCEDURE SaveMultipleChoices @SubmissionID INT, @Choices CSV NVARCHAR(MAX), -- Comma-separated values @ErrorMessage NVARCHAR(4000) OUTPUT AS BEGIN BEGIN TRY BEGIN TRANSACTION -- Split CSV values and insert INSERT INTO UserChoices (SubmissionID, ChoiceValue) SELECT @SubmissionID, value FROM STRING_SPLIT(@Choices, ',') COMMIT TRANSACTION SET @ErrorMessage = NULL END TRY BEGIN CATCH ROLLBACK TRANSACTION SET @ErrorMessage = ERROR_MESSAGE() END CATCH ENDpublic void SaveChoices(int submissionId, List selectedChoices) { using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); SqlCommand cmd = new SqlCommand("SaveMultipleChoices", conn); cmd.CommandType = CommandType.StoredProcedure; // Convert list to comma-separated string string choicesCsv = string.Join(",", selectedChoices); // Add parameters cmd.Parameters.AddWithValue("@SubmissionID", submissionId); cmd.Parameters.AddWithValue("@ChoicesCSV", choicesCsv); cmd.Parameters.Add("@ErrorMessage", SqlDbType.NVarChar, 4000).Direction = ParameterDirection.Output; cmd.ExecuteNonQuery(); if (cmd.Parameters["@ErrorMessage"].Value != DBNull.Value) { throw new Exception(cmd.Parameters["@ErrorMessage"].Value.ToString()); } } }CSV Handling: Uses
STRING_SPLIT()(SQL Server 2016+) to parse comma-separated valuesTransaction Management: Ensures all inserts succeed or fail together
Error Handling: Returns detailed error messages
Scalability: Handles any number of choices
Tuhin PaulRank #7 · 71.9K reputationPosted Feb 26, 2025, 5:25 AM EST
Part - 2
Ivonne AspilcuetaRank #4,887 · 320 reputationPosted Feb 25, 2025, 2:18 PM EST
Hello,
It is giving this error:
System.Data.SqlClient.SqlException: 'Conversion failed when converting the nvarchar value 'Branch Deposit Checks' to data type int.'
Any thoughts?
Shem OtienoRank #2,138 · 667 reputationPosted Feb 27, 2025, 4:10 AM EST
Right ! Ivonne,here’s a general approach to save a list of multiple choices as rows with the same ID in a database using a stored procedure.
Let's assume you have a table structure like this:
sql
CREATE TABLE Choices ( ID INT, Choice VARCHAR(255) );And you have a list of choices to save for a specific ID. You can create a stored procedure to handle this task.
Step 1: Create the Stored Procedure
Here's an example of a stored procedure to save the data:
sql
CREATE PROCEDURE SaveChoices @ID INT, @Choices VARCHAR(MAX) AS BEGIN SET NOCOUNT ON; -- Split the @Choices string into individual choices and insert into the Choices table DECLARE @Choice VARCHAR(255) DECLARE @Pos INT SET @Choices = LTRIM(RTRIM(@Choices)) + ',' SET @Pos = CHARINDEX(',', @Choices, 1) WHILE @Pos > 0 BEGIN SET @Choice = LTRIM(RTRIM(LEFT(@Choices, @Pos - 1))) INSERT INTO Choices (ID, Choice) VALUES (@ID, @Choice) SET @Choices = RIGHT(@Choices, LEN(@Choices) - @Pos) SET @Pos = CHARINDEX(',', @Choices, 1) END ENDStep 2: Call the Stored Procedure from Your Form
When you submit the form, collect the list of choices and concatenate them into a single string separated by commas. Then, call the stored procedure and pass the ID and concatenated choices string.
Example in C# (ASP.NET):
protected void SubmitButton_Click(object sender, EventArgs e) { int id = // get your ID List choices = // get your list of choices string choicesString = string.Join(",", choices); using (SqlConnection conn = new SqlConnection("your_connection_string")) { SqlCommand cmd = new SqlCommand("SaveChoices", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@ID", id); cmd.Parameters.AddWithValue("@Choices", choicesString); conn.Open(); cmd.ExecuteNonQuery(); conn.Close(); } }Step 3: Ensure Data Integrity
Make sure to validate the choices and handle any potential errors, such as SQL injection attacks, by using parameterized queries as shown above.
Ivonne AspilcuetaRank #4,887 · 320 reputationPosted Feb 27, 2025, 12:18 PM EST
Sorry everyone who is tryng to help me, it is hard to explin by comment instead posting my code, but forum does not allow me to post ant code anymore, I guees I need points for that.
If you know a way to share my code, please let me know. Thank you so much for your help.