2010-06-17 36 views
1

下面是一個代碼片段,用於將表作爲參數傳遞給可在Sql Server 2008中使用的查詢。儘管我對「SELECT id.custid FROM @custids ID「。爲什麼它使用id.custid和@custids id ...?C#和SQL - 從表中選擇參數

private static void datatable_example() 
{ 

    string [] custids = {"ALFKI", "BONAP", "CACTU", "FRANK"}; 

    DataTable custid_list = new DataTable(); 
    custid_list.Columns.Add("custid", typeof(String)); 

    foreach (string custid in custids) { 
     DataRow dr = custid_list.NewRow(); 
     dr["custid"] = custid; 
     custid_list.Rows.Add(dr); 
    } 

    using(SqlConnection cn = setup_connection()) 
    { 
     using(SqlCommand cmd = cn.CreateCommand()) 
     { 

     cmd.CommandText = 
      @"SELECT C.CustomerID, C.CompanyName 
      FROM Northwind.dbo.Customers C 
      WHERE C.CustomerID IN (SELECT id.custid FROM @custids id)"; 
     cmd.CommandType = CommandType.Text; 

     cmd.Parameters.Add("@custids", SqlDbType.Structured); 
     cmd.Parameters["@custids"].Direction = ParameterDirection.Input; 
     cmd.Parameters["@custids"].TypeName = "custid_list_tbltype"; 
     cmd.Parameters["@custids"].Value = custid_list; 

     using (SqlDataAdapter da = new SqlDataAdapter(cmd)) 
     using (DataSet  ds = new DataSet()) { 
      da.Fill(ds); 
      PrintDataSet(ds); 
     } 
     } 
    } 

回答

3

子查詢中的'id'只是一個別名。

就像在主FROM子句中使用'C'作爲別名一樣,並使用'C.CustomerID'。

子查詢也可以同樣一直

SELECT custid 
FROM @custids 
+0

非常感謝您! – j03m 2010-06-17 05:09:23