从另一个表和值插入表中

时间:2013-02-21 08:44:04

标签: c# asp.net sql sql-server sql-insert

我想将表数据和文本框值插入另一个表中。我正在尝试插入命令,如下所示,但它无法正常工作。

Insert into 
     Table_UserAnswer 
      (
         UserQuizID, 
         QuizID, 
         QuestionID, 
         Title, 
         Answer1, 
         Answer2, 
         Answer3, 
         Answer4,
         CorrectAnswer
       ) 
         '" + m.ToString() + 
      "', 
      select 
         top 5 QuizID, 
         QuestionID, 
         Title, 
         Answer1,
         Answer2,
         Answer3,
         Answer4,
         CorrectAnswer 
     from 
         [Table_Question] 
     order by 
          newid()"

2 个答案:

答案 0 :(得分:3)

使用INSERT INTO...SELECT语句,

INSERT INTO 
    Table_UserAnswer 
    (
      UserQuizID, 
      QuizID, 
      QuestionID, 
      Title, 
      Answer1, 
      Answer2, 
      Answer3, 
      Answer4, 
      CorrectAnswer)  
    SELECT TOP 5 
      'UserQuizIDValue', 
      QuizID, 
      QuestionID, 
      Title,
      Answer1,
      Answer2,
      Answer3,
      Answer4,
      CorrectAnswer 
    FROM   
      Table_Question
    ORDER BY 
      newid()

UserQuizIDValue的值来自m.ToString()

答案 1 :(得分:0)

INSERT INTO TestTable(Col1,Col2) SELECT Col1,Col1 来自Person.Contact

您必须确保Insert查询中的列数应与Select语句相同,除非您有任何标识列。

在您的情况下,Select语句中缺少“UserQuizID”。