-2

我有一个单列数据表,我想使用 sqlparametercollection 在 SQL where 子句中传递这个数据表。请帮忙。下面是我的代码:

public DataTable getCatsByDepts(DataTable _Depts)
    {

        SqlConnection conn = new SqlConnection("Server=ax12d;Database=DemoDataAx;Trusted_Connection=True;");
        SqlCommand cmd = new SqlCommand("Select Level2 as Category from Mtq_RetailHierarchy Where Level1 IN (@Depts)", conn);
        foreach (DataRow row in _Depts.Rows)
        {
            cmd.Parameters.Clear();
            cmd.Parameters.AddWithValue("Department", row.Field<string>("Department"));
            //cmd.ExecuteNonQuery();
        }


        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataTable SelectedCatsData = new DataTable();
        da.Fill(SelectedCatsData);
        return SelectedCatsData;

    }`
4

2 回答 2

1

如果您使用的是 SQL Server 2008 或更高版本,则可以使用表值参数

SqlConnection conn = new SqlConnection("Server=ax12d;Database=DemoDataAx;Trusted_Connection=True;");

SqlCommand cmd = new SqlCommand(@"Select Level2 as Category 
                                  from Mtq_RetailHierarchy 
                                  Where Level1 IN (SELECT Department 
                                                   From @Depts)", conn);

cmd.Parameters.Clear();
SqlParameter param cmd.Parameters.AddWithValue("@Depts", _Depts);
param.SqlDbType = SqlDbType.Structured;
param.TypeName = "dbo.Departments"; //This can either be a table or a User Defined Type


SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable SelectedCatsData = new DataTable();
da.Fill(SelectedCatsData);
return SelectedCatsData;
于 2013-01-02T19:42:16.813 回答
0

假设您有DataTable一列,并且您想在 db-table 中插入所有行。一个简单的方法(也假设 Sql-Server 为 rdbms):

using(var con= new SqlConnection(connectionString))
using(var insertCommand = new SqlCommand("INSERT INTO dbo.Table VALUES(@Colname)", con))
{
    con.Open();
    foreach(DataRow row in table.Rows)
    {
        insertCommand.Parameters.Clear();
        insertCommand.Parameters.AddWithValue("Colname", row.Field<string>("Colname"));
        insertCommand.ExecuteNonQuery();
    }
}
于 2012-12-10T13:46:25.520 回答