插入查询如何将数据复制到另一个表

时间:2018-04-16 11:44:54

标签: c# sql

我正在尝试将旧数据从一个表ManualAdjustments存档到另一个表。代码可以作为存储过程正常工作,但需要从存储过程中将其更改回来。我是否需要在SQL查询或嵌套查询中执行新行?

错误代码 - 未将对象引用设置为对象的实例

    //Archive MA Data 
            string connectionString0 = ConfigurationManager.ConnectionStrings["PlusConnectionString"].ConnectionString;
            string UpdateSql0 = "Insert into MAArchive (MAIndex, PTLName, PTLStaffID, PTLPayrollID, CJSID, CampusOccurred, DeptOccurred, DateOccurred, CourseDetails, Duration, ValueOfDuration, Grade, CostCentre, Reason, Comment, RatePerHour, Pay, MASubmittedBy, MADateSubmitted, Status, CheckedBy, CheckedDate, ApprovedBy, ApprovedDate, DeniedBy, DeniedDate, PayPeriod, AcademicYear) select * from ManualAdjustments Where Status='Approved' or Status ='Denied' and PayPeriod = @PayrollPeriodCurrent0";
            //
            SqlConnection con0 = new SqlConnection(connectionString0);

            //
            SqlCommand cmd0 = new SqlCommand();
            cmd0.Connection = con0;
            cmd0.CommandType = CommandType.Text;
            cmd0.CommandText = UpdateSql0;

            SqlParameter PayrollPeriodCurrent0 = new SqlParameter("@PayrollPeriodCurrent0", SqlDbType.VarChar, 20);
            PayrollPeriodCurrent0.Value = Session["PayrollPeriod"].ToString();
            cmd0.Parameters.Add(PayrollPeriodCurrent0);

4 个答案:

答案 0 :(得分:0)

如果您将"Insert ..."更改为@"Insert ...(请注意@ -sign),您会得到一个可能跨越多行的字符串。否则你需要将字符串分解为几个字符串(每行一个)并将它们添加为:

"Select * from "
+ "sys.tables where 1=1 and 'a' ='a'";

答案 1 :(得分:0)

您可以使用@字符来允许查询跨越多行,例如


    string query = @"Select * from
            sys.tables where 1=1 and 'a' ='a'";

答案 2 :(得分:0)

试试这个..

INSERT INTO table2 (column1, column2, column3, ...)
SELECT column1, column2, column3, ...
FROM table1
WHERE condition;

答案 3 :(得分:0)

如果两个表都是真正相同的模式:

INSERT INTO newTable SELECT * FROM oldTable 否则,您必须指定列名称(如果您为所有列指定值并按照与newTable架构相同的顺序选择列,则newTable的列列表是可选的):

INSERT INTO newTable(col1,col2,col3) SELECT column1,column2,column3 来自oldTable