你可以使用Table-Valued Parameters in SQL Server 2008 (ADO.NET)。
SQL
CREATE TYPE [dbo].[MyTableType] AS TABLE
(
[SomeName] NVARCHAR(50),
[SomeType] NVARCHAR(50)
)
CREATE TABLE [dbo].[MyTable]
(
[SomeName] NVARCHAR(50),
[SomeType] NVARCHAR(50)
)
INSERT [dbo].[MyTable]
VALUES ('Name1', 'Type1'),
('Name2', 'Type2'),
('Name3', 'Type3'),
('Name4', 'Type4')
C#
var values = new List<Tuple<string, string>> { Tuple.Create("Name1", "Type1"), Tuple.Create("Name2", "Type2"), Tuple.Create("Name3", "Type3") };
var dataTable = new DataTable();
dataTable.Columns.Add(new DataColumn("SomeName", typeof(string)));
dataTable.Columns.Add(new DataColumn("SomeType", typeof(string)));
values.ForEach(v => dataTable.Rows.Add(v.Item1, v.Item2));
using (var connection = new SqlConnection(@"Data Source=.;Initial Catalog=Tom;Integrated Security=True"))
{
using (var command = new SqlCommand())
{
command.Connection = connection;
command.CommandText =
"SELECT * " +
"FROM [dbo].[MyTable] mt " +
"INNER JOIN @MyTableType mtt " +
" ON mt.[SomeName] = mtt.[SomeName] " +
" AND mt.[SomeType] = mtt.[SomeType]";
SqlParameter parameter = command.Parameters.AddWithValue("@MyTableType", dataTable);
parameter.SqlDbType = SqlDbType.Structured;
parameter.TypeName = "[dbo].[MyTableType]";
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine("mt.[SomeName]: {0}, mt.[SomeType]: {1}, mtt.[SomeName]: {2}, mtt.[SomeType]: {3}",
reader.GetString(0), reader.GetString(1), reader.GetString(2), reader.GetString(3));
}
}
}
Console.ReadKey();
我正在考慮這樣做並加入。我希望有一個簡單的SQL語句可以轉化爲我可以用於Entity Framework的東西,但它看起來越來越像我將不得不訴諸於存儲過程。 – Dismissile
@Dismissile,我添加了一些示例代碼。 –