需要动态插入查询以下代码

时间:2014-11-06 07:21:37

标签: c# sql

对于以下代码,我在执行之前并不知道列表框项,因此我需要动态查询来选择以下代码;

            string selectedTable = cmbImportItemList.Text;

            string col1 = opLstCsl3.Items[0].ToString();
            string col2 = opLstCsl3.Items[1].ToString();
            string col3 = opLstCsl3.Items[2].ToString();
            string col4 = opLstCsl3.Items[3].ToString();
            string col5 = opLstCsl3.Items[4].ToString();
            string col6 = opLstCsl3.Items[5].ToString();
            string col7 = opLstCsl3.Items[6].ToString();
            string col8 = opLstCsl3.Items[7].ToString();
            //string[] coll = new string[100];
            //string col9 = opLstCsl3.Items[8].ToString();
            //'"+col1+"','"+col2+"','"+col3+"','"+col4+"'
            using (SqlDataAdapter adater = new SqlDataAdapter("Select " + col1 + "," + col2 + "," + col3 + "," + col4 + "," + col5 + "," + col6 + "," + col7 + "," + col8 + " from " + selectedTable, new SqlConnection(Properties.Settings.Default.connectionstring2)))
            {
                adater.Fill(dttt);
            }

1 个答案:

答案 0 :(得分:0)

我为您的查询编写了一个存储过程,首先在您的数据库中执行它,

CREATE PROCEDURE GetData @colName nvarchar(500) = NULL,@tableName nvarchar(50)=NULL
AS
DECLARE @sqlText nvarchar(1000); 
SET @sqlText = N'SELECT ' + @colName + ' FROM ' + @tableName
Exec (@sqlText)
GO

并使您的列以逗号分隔,如下所示

string selectedTable = cmbImportItemList.Text;
string columns = string.Empty;
foreach (var item in pLstCsl3.Items)
{
   columns += item + ',';
}

最后调用存储过程如下,

using (SqlConnection con = new SqlConnection(Properties.Settings.Default.connectionstring2)) {
    con.Open();

    SqlCommand cmd  = new SqlCommand("GetData", con);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.Add(new SqlParameter("@colName", columns));
    cmd.Parameters.Add(new SqlParameter("@tableName", selectedTable));

    using (SqlDataReader rdr = cmd.ExecuteReader()) {

        while (rdr.Read())
        {
            // do what ever you want with your records.
        }
    }
}

希望有所帮助

如果您想了解存储过程,请参阅以下链接, http://www.codeproject.com/Articles/126898/Sql-Server-How-to-write-a-Stored-procedure-in-Sql

由于 斯万