如何在datatable asp.net mvc中添加新列

时间:2016-01-11 01:47:14

标签: c# sql-server asp.net-mvc datatable

我有这段代码:

public ActionResult RcColdis() {
string constr = @"Data Source=192.168.52.197,1433;Network Library=DBMSSOCN;Initial Catalog=DB_ADRIAN;User ID=adrian;Password=password;";

using (SqlConnection con = new SqlConnection(constr))
{
    using (SqlCommand cmd = new SqlCommand("select a.secCode, b.[Haircut (%)],c.[Absolute IDR (Miliar)] from openquery(PDC_MYAPPS,'select secCode from mii.secReq')a left join (select * from RC_Saham)b on a.secCode=b.kode left join (select * from Absolute_IDR)c on b.kode=c.[Kode Saham]where b.[Haircut (%)] is not null union select a.code_Ic,a. PERC_HRCT, case  a. PERC_HRCT when 100 then 20 end from openquery(MANTARAY,'select b.code_ic, a.PERC_HRCT from cminstruments a, instrument_codes b where a.ID_CMI_CAPCO = b.INS_ID_INS_CAPCO')a left join (select * from Absolute_IDR)b on a.code_Ic = b.[Kode Saham]where code_Ic in (select a.secCode from openquery(PDC_MYAPPS,'select secCode from mii.secReq')a left join (select * from RC_Saham )b on a.secCode=b.kode left join (select * from Absolute_IDR)c on b.kode = c.[Kode Saham] where c.[Absolute IDR (Miliar)] is null )"))
    {
        using (SqlDataAdapter sda = new SqlDataAdapter())
        {
            cmd.Connection = con;
            sda.SelectCommand = cmd;

            using (DataTable dt = new DataTable())
            {
                sda.Fill(dt);

                //Build the Text file data.
                string txt = string.Empty;

                //Add new line.
                foreach (DataRow row in dt.Rows)
                {
                     foreach (DataColumn column in dt.Columns)
                     {
                         //Add the Data rows.
                         txt += row[column.ColumnName].ToString() + "|";
                     }

                     //Add new line.
                     txt += "\r\n";
                }

                //Download the Text file.
                Response.Clear();
                Response.Buffer = true;
                Response.AddHeader("content-disposition", "attachment;filename=SqlExport.txt");
                Response.Charset = "";
                Response.ContentType = "application/text";
                Response.Output.Write(txt);
                Response.Flush();
                Response.End();
            }
       }
    }
}  

return View("Index");
}

它会将数据从数据库导出到datatable,然后导出到txt文件。我得到的结果包括两列:

asdasd|12112
sdfsfs|2342
asdsgf|3455
gfhghj|87897
ghjghj|45654

我想在中间添加新列,其值为' 10'对于所有行。我该怎么做?

1 个答案:

答案 0 :(得分:1)

如果希望所有记录的常量值为10,则可以更新SQL查询以将该值作为列返回。

"select a.secCode,10 as MyValue, b.[Haircut (%)],c.[Absolute IDR (Miliar)] from openquery"