Marius Vasile

Marius Vasile

  • 590
  • 1.9k
  • 148.9k

Insert into one table multiple random rows from other table

Aug 17 2023 11:02 AM

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?


Answers (8)