假设我有一个包含3列的表格:Id,类别,名称。
我想以这种方式查询表:为我获取{ Category = "Cat1" AND Name = "ABC" }OR{ Category = "Cat2" AND Name = "ABC" }或OR的行 { Category = "Cat2" AND Name = "DEF" }
{ Category = "Cat1" AND Name = "ABC" }
{ Category = "Cat2" AND Name = "ABC" }
{ Category = "Cat2" AND Name = "DEF" }
如何?不必求助于WHERE OR 我想使用的庞大列表IN…但是可以将其与2列一起使用吗?
WHERE OR
IN
谢谢!
您可以创建一个临时表
create table #temp (Category varchar(50), Name varchar(50)) insert into #temp values ('Cat1', 'abc'), ('Cat2', 'cde'), ('Cat3', 'eee')
然后加入你的主表
select * from table1 inner join #temp on table1.Category = #temp.Category and table1.Name = #temp.Name
如果要从代码中使用该方法,则可以使用表参数进行操作。
定义表类型:
CREATE TYPE dbo.ParamTable AS TABLE ( Category varchar(50), Name varchar(50) )
和一个存储的proc将读取数据:
create procedure GetData(@param dbo.ParamTable READONLY) AS select * from table1 inner join @param p on table1.Category = p.Category and table1.Name = p.Name
然后,您可以使用C#代码中的代码,例如:
using (var conn = new SqlConnection("Data Source=localhost;Initial Catalog=Test2;Integrated Security=True")) { conn.Open(); DataTable param = new DataTable(); param.Columns.Add(new DataColumn("Category", Type.GetType("System.String"))); param.Columns.Add(new DataColumn("Name", Type.GetType("System.String"))); param.Rows.Add(new object[] { "Cat1", "abc" }); using (var command = conn.CreateCommand()) { command.CommandText = "GetData"; command.CommandType = CommandType.StoredProcedure; command.Parameters.AddWithValue("@param", param); using (var reader = command.ExecuteReader()) { // reading here } } }