Ado.Net查询语句使用临时表做条件
using System; using System.Data; using System.Data.SqlClient; using System.Text; namespace WindowsFormsApp1 { public class SQLHelper { static string connStr = "Data Source='.';Initial Catalog='DBName';User ID='sa';Password='123456';Connect Timeout=60000;"; /// <summary> /// 带临时查询表sql /// </summary> /// <param name="Sql"> 查询sql </param> /// <param name="CreateTmpTablesql"> 创建临时表语句 </param> /// <param name="TmpTableName">在数据库中创建临时表sql</param> /// <param name="TmpData">临时表数据</param> public static DataSet GetDataTmpTableSqlBulkCopy(string Sql, string CreateTmpTablesql, string TmpTableName, DataTable TmpData) { //构造SQL语句 StringBuilder sb = new StringBuilder(); #region 处理临时表数据为空则不处理临时表 using (SqlConnection thisConn = new SqlConnection(connStr)) { try { thisConn.Open(); if (!string.IsNullOrEmpty(CreateTmpTablesql) && !string.IsNullOrEmpty(TmpTableName) && TmpData != null) { //创建临时表 SqlCommand cmd = new SqlCommand(CreateTmpTablesql.ToString(), thisConn); object returnValue = cmd.ExecuteScalar(); // 使用 SqlBulkCopy 批量保存临时表数据 SqlBulkCopy bulkCopy = new SqlBulkCopy(thisConn); bulkCopy.DestinationTableName = TmpTableName; bulkCopy.BatchSize = TmpData.Rows.Count; bulkCopy.WriteToServer(TmpData); } //查询带临时表的sql DataSet ds = new DataSet(); SqlDataAdapter da = new SqlDataAdapter(Sql, thisConn); da.Fill(ds); return ds; } catch (Exception ex) { return null; } finally { thisConn.Close(); } } #endregion } } }
// 测试调用 private void Button1_Click(object sender, EventArgs e) { // 创建临时表sql语句 string CreateTmpTablesql = @"select top 1 MethodName into #tmpTable from AbpAuditLogs"; DataTable dataTable = new DataTable(); dataTable.Columns.Add("MethodName"); foreach (var item in "Index,GetAll".Split(',')) { DataRow row = dataTable.NewRow(); row["MethodName"] = item; dataTable.Rows.Add(row); } string sql = @"select * from AbpAuditLogs a where exists ( select * from #tmpTable tmp where a.MethodName= tmp .MethodName ) "; DataSet ds = SQLHelper.GetDataTmpTableSqlBulkCopy(sql, CreateTmpTablesql, "#tmpTable", dataTable); }