So, I tried to find a solution for this for two days and I failed to have one functioning. My query is:
string sqlQuery = "INSERT INTO tblTestDetail (IdIntrebare, IdRaspunsCorect, IdUsetTest) SELECT ti.IdIntrebare AS IdIntrebare, tr.IdRaspuns AS IdRaspunsCorect, @IdUserTest FROM (SELECT TOP5 * FROM tblIntrebare ti ORDER BY NEWID()) JOIN tblRaspuns tr ON ti.IdIntrebare=tr.IdIntrebare WHERE tr.Raspuns='DA')";I have 3 table, tblIntrebare, tblRaspuns and tblTestDetail. tblIntrebare and tblRaspuns are related through FK IdIntrebare
tblTestDetail contains 4 fields, its own Id, FK IdUserTest, IdIntrebare and IdRaspunsCorect
What I want to do select 5 random IdIntrebare and its respective IdRaspuns from tblIntrebare JOIN tblRaspuns and INSERT INTO tblTestDetail along with IdUserTest which is always provided by
cmd.Parameters.AddWithValue("@IdUserTest", txtIdUserTest.Text);I am using asp.net c# but is mainly sql server issue. How it should be done, please?


Mohammad HussainRank #513 · 4.8K reputationPosted Aug 17, 2023, 8:15 AM EDT
Try this.
protected void AddDetaliiTest() { string sqlQuery = "INSERT INTO tblTestDetail (IdIntrebare, IdRaspunsCorect, IdUserTest) SELECT ti.IdIntrebare AS IdIntrebare, tr.IdRaspuns AS dRaspunsCorect, @IdUserTest FROM ( SELECT TOP 5 * FROM tblIntrebare ORDER BY NEWID() ) ti JOIN tblRaspuns tr ON ti.IdIntrebare = tr.IdIntrebare WHERE tr.Raspuns = 'DA';"; using (SqlConnection conn = new SqlConnection(connString)) { try { int userIdTest; if (Int32.TryParse(txtIdUserTest.Text, out userIdTest)) { using (SqlCommand cmd = new SqlCommand(sqlQuery, conn)) { cmd.CommandType = CommandType.Text; cmd.Parameters.AddWithValue("@IdUserTest", userIdTest); conn.Open(); int result = cmd.ExecuteNonQuery(); if (result > 0) { ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Record Inserted Successfully')", true); } } } else { // Handle the case where txtIdUserTest.Text cannot be parsed to an integer ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Invalid User Test ID')", true); } } catch (Exception ex) { // Handle any exceptions that may occur during database interaction ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('An error occurred: " + ex.Message + "')", true); } } }Abhishek YadavRank #217 · 11.3K reputationPosted Aug 17, 2023, 7:26 AM EDT
To achieve your goal of selecting 5 random IdIntrebare and its respective IdRaspuns from tblIntrebare and tblRaspuns, and then inserting them into tblTestDetail along with the provided IdUserTest, you can use the following SQL query:
string sqlQuery = "INSERT INTO tblTestDetail (IdIntrebare, IdRaspunsCorect, IdUserTest) SELECT TOP 5 ti.IdIntrebare AS IdIntrebare, tr.IdRaspuns AS IdRaspunsCorect, @IdUserTest FROM tblIntrebare ti JOIN tblRaspuns tr ON ti.IdIntrebare = tr.IdIntrebare WHERE tr.Raspuns = 'DA' ORDER BY NEWID()";This query performs the following steps:
Selects the top 5 random rows from tblIntrebare by using the
TOP 5clause and ordering them randomly withORDER BY NEWID().Joins the selected rows with tblRaspuns using the matching IdIntrebare values.
Filters the rows based on the condition
tr.Raspuns = 'DA'to select only the rows with Raspuns equal to 'DA'.Inserts the selected IdIntrebare, IdRaspunsCorect, and the provided IdUserTest into tblTestDetail.
Make sure to execute this SQL query using a SqlCommand object with the necessary parameter values specified.
Marius VasileRank #785 · 2.9K reputationPosted Aug 17, 2023, 7:52 AM EDT
Thank you Mohammad, I get no error nut no data is written. Have I mentioned that all values should be int type?
I tried to convert
cmd.Parameters.AddWithValue("@IdUserTest", txtIdUserTest.Text);and use it as
int p = Int32.Parse(txtIdUserTest.Text);but I still have no data written. My post is:
protected void AddDetaliiTest () { string sqlQueryQ = "INSERT INTO tblTestDetail (IdIntrebare, IdRaspunsCorect, IdUserTest) SELECT TOP 5 ti.IdIntrebare AS IdIntrebare, tr.IdRaspuns AS IdRaspunsCorect, @IdUserTest FROM tblIntrebare ti JOIN tblRaspuns tr ON ti.IdIntrebare = tr.IdIntrebare WHERE tr.Raspuns = 'DA' ORDER BY NEWID()"; string sqlQuery = "INSERT INTO tblTestDetail(IdIntrebare, IdRaspunsCorect, IdUserTest) SELECT ti.IdIntrebare AS IdIntrebare, tr.IdRaspuns AS IdRaspunsCorect, @IdUserTest FROM(SELECT TOP 5 * FROM tblIntrebare ORDER BY NEWID()) ti JOIN tblRaspuns tr ON ti.IdIntrebare = tr.IdIntrebare WHERE tr.Raspuns = 'DA';"; using (SqlConnection conn = new SqlConnection(connString)) { int p = Int32.Parse(txtIdUserTest.Text); using (SqlCommand cmd = new SqlCommand(sqlQuery, conn)) { cmd.CommandType = CommandType.Text; cmd.Parameters.AddWithValue("@IdUserTest", txtIdUserTest.Text); conn.Open(); int result = cmd.ExecuteNonQuery(); if (result > 0) { ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Record Inserted Successfully')", true); } conn.Close(); } } }Marius VasileRank #785 · 2.9K reputationPosted Aug 17, 2023, 7:45 AM EDT
Thank for the answer Abhishek, I get no error but no data is written. I will look into it more to see if I'm doing domething wrong
Marius VasileRank #785 · 2.9K reputationPosted Aug 17, 2023, 8:27 AM EDT
Thanks again Mohammad, it simply does not add values. I am sure txtIdUserText has value. Table tblTestDetail is
CREATE TABLE [dbo].[tblTestDetail] ( [IdTestDetail] INT IDENTITY (1, 1) NOT NULL, [IdIntrebare] INT NOT NULL, [IdRaspunsCorect] INT NOT NULL, [IdUserTest] INT NOT NULL, PRIMARY KEY CLUSTERED ([IdTestDetail] ASC), CONSTRAINT [FK_tblTestDetail_tblUserTest_IdUserTest] FOREIGN KEY ([IdUserTest]) REFERENCES [dbo].[tblUserTest] ([IdUserTest]) ON DELETE CASCADE );Marius VasileRank #785 · 2.9K reputationPosted Aug 17, 2023, 8:46 AM EDT
I had an error, was not Raspuns='DA' but Corect='DA' and now is working perfectly. Thank you very much both of you
Mohammad HussainRank #513 · 4.8K reputationPosted Aug 17, 2023, 7:39 AM EDT
Could you please try this SQL Query. I have made minor change in your query. It should work. Thanks...
INSERT INTO tblTestDetail (IdIntrebare, IdRaspunsCorect, IdUserTest)
SELECT ti.IdIntrebare AS IdIntrebare, tr.IdRaspuns AS IdRaspunsCorect, @IdUserTest
FROM (
SELECT TOP 5 * FROM tblIntrebare ORDER BY NEWID()
) ti
JOIN tblRaspuns tr ON ti.IdIntrebare = tr.IdIntrebare
WHERE tr.Raspuns = 'DA';
Cr BhargaviRank #420 · 5.9K reputationPosted Aug 17, 2023, 11:32 AM EDT
using System; using System.Data; using System.Data.SqlClient; namespace YourNamespace { class Program { static void Main(string[] args) { string connectionString = "Your_Connection_String"; string sqlQuery = "INSERT INTO tblTestDetail (IdIntrebare, IdRaspunsCorect, IdUsetTest) " + "SELECT ti.IdIntrebare AS IdIntrebare, tr.IdRaspuns AS IdRaspunsCorect, @IdUserTest " + "FROM (SELECT TOP 5 * FROM tblIntrebare ti ORDER BY NEWID()) ti " + "JOIN tblRaspuns tr ON ti.IdIntrebare = tr.IdIntrebare " + "WHERE tr.Raspuns = 'DA'"; using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); using (SqlCommand cmd = new SqlCommand(sqlQuery, connection)) { // Assuming txtIdUserTest.Text holds the user test ID cmd.Parameters.AddWithValue("@IdUserTest", txtIdUserTest.Text); int rowsAffected = cmd.ExecuteNonQuery(); Console.WriteLine($"{rowsAffected} rows inserted into tblTestDetail."); } } } } }