假设我有一个包含 3 列的表:Id、Category、Name。
我想这样查询表:
给我的行
{ Category = "Cat1"AND Name = "ABC"}
或 { Category = "Cat2"AND Name = "ABC"}
OR { Category = "Cat2 "AND Name = "DEF"}
如何?无需求助于大量的 WHERE OR
我正在考虑使用 IN
...但是是否可以将它与 2 列结合使用?
谢谢!
最佳答案
你可以创建一个临时表
create table #temp (Category varchar(50), Name varchar(50))
insert into #temp values ('Cat1', 'abc'), ('Cat2', 'cde'), ('Cat3', 'eee')
然后加入你的主 table
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) )
和一个将读取数据的存储过程:
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
}
}
}
关于sql - 如何使用键值对列表查询数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20293673/