2013-08-16 51 views
0

在TSQL我可以这样写:C#语法TSQL “IN” 参数

Select * from mytablename M where M.field in (1, 5, 8, 56) 

如果我想要做同样的事情在参数C#中,什么是语法?

+1

你的意思是'IN(@ P1,P2 @,@ P3,P4 @)'? –

+0

只是我的脑溢出了.. –

+0

它有助于当downvotes伴随着什么是缺乏评论。 – hatchet

回答

1

SQL Server 2008有一个名为Table-Valued Parameters的特性。你在SQL Server中创建一个“特殊类型”,然后你可以传递一个DataTable作为参数,包含你想要的所有值。

你可以用这种方式:

在DB这样做:CREATE TYPE dbo.IntArray AS TABLE (Value INT NOT NULL)

您的查询必须改变,以这样的:CustomerID IN (SELECT Value FROM @1)

// Your array of IDs 
int[] ids = new[] { 1, 2, 3, 4, 5, 6, 7, 10 }; 

using (var connection = new SqlConnection("Initial Catalog=AdventureWorksLT2012;Integrated Security=True")) 
{ 
    connection.Open(); 

    using (var command = new SqlCommand("SELECT CustomerID FROM SalesLT.Customer WHERE CustomerID IN (SELECT Value FROM @1)", connection)) 
    { 
     // An untyped Datatable 
     var dt = new DataTable(); 

     // With a single column 
     dt.Columns.Add(); 

     // Copy your IDs in the DataTable 
     foreach (var v in ids) 
     { 
      dt.Rows.Add(v); 
     } 

     // Create the Table-Valued Parameter 
     var param = command.Parameters.AddWithValue("@1", dt); 
     param.SqlDbType = SqlDbType.Structured; 
     param.TypeName = "dbo.IntArray"; 

     using (var reader = command.ExecuteReader()) 
     { 
      while (reader.Read()) 
      { 
       int id = (int)reader[0]; 

       Console.WriteLine(id); 
      } 
     } 
    } 
} 

从技术上讲,你可以改变你的查询即使在像

INNER JOIN @1 Par ON CustomerID = Par.Value 

这样做的好处是您可以创建多列DataTable和Table-Valued参数,并同时在多个条件下执行搜索。

(注意,是因为它是基于微软的AdventureWorks的DB工作的例子我的代码过长)