修改查询以使用INSERT INTO

时间:2013-08-13 13:36:54

标签: c# sql sql-server database sql-insert

我开发了一个非常复杂的查询,现在很难修改它以使用INSERT INTO语句。

查询(VS语法):

           @"SELECT s.TagID, se.SessionID, " +
           " @todaysDate " +
           " AS ScanningTime " +
           " FROM (((Student s " +
           " LEFT JOIN [CourseID-ModuleID] cm ON s.CourseID = cm.CourseID) " +
           " LEFT JOIN [ModuleID-SessionID] ms ON cm.ModuleID = ms.ModuleID) " +
           " LEFT JOIN [Session] se ON ms.SessionID = se.SessionID) " +
           " WHERE s.TagID = @tagNo " +
           " AND se.SessionDate = cast(getdate() as date) " +
           " AND se.SessionTimeStart <= @Plus30Min " +
           " AND se.SessionTimeEnd >= @Plus30Min ";

查询运行完美,但我想将查询结果放入空表Attendance中,该表已存在于数据库中。

Attendance table data types

TagID - int
SessionID - varchar
ScanningTime - datetime.

请注意,考勤表的数据类型与其他表数据类型匹配。

我尝试在SELECT语句之前放置“INSERT INTO考勤(s.TagID,se.SessionID,ScanningTime)”,但我的查询不会产生任何结果。

修改我的查询以包含INSERT INTO语句的正确方法是什么?感谢

修改

您的所有答案和建议非常有帮助。谢谢!

3 个答案:

答案 0 :(得分:1)

删除(s.TagID, se.SessionID, ScanningTime),然后在选择

之前添加INSERT INTO Attendance
@"INSERT INTO Attendance
 SELECT s.TagID, se.SessionID, "
 etc...

答案 1 :(得分:0)

INSERT INTO table2
(column_name(s))
SELECT column_name(s)
FROM table1;

答案 2 :(得分:0)

您可以参考以下代码:

@"INSERT INTO Attendance(
   TagID , 
   SessionID,
   ScanningTime )
SELECT s.TagID, se.SessionID, " +
           " @todaysDate " +
           " AS ScanningTime " +
           " FROM (((Student s " +
           " LEFT JOIN [CourseID-ModuleID] cm ON s.CourseID = cm.CourseID) " +
           " LEFT JOIN [ModuleID-SessionID] ms ON cm.ModuleID = ms.ModuleID) " +
           " LEFT JOIN [Session] se ON ms.SessionID = se.SessionID) " +
           " WHERE s.TagID = @tagNo " +
           " AND se.SessionDate = cast(getdate() as date) " +
           " AND se.SessionTimeStart <= @Plus30Min " +
           " AND se.SessionTimeEnd >= @Plus30Min ";