C# C和SQL-sub从表参数中选择
下面是一段代码片段,用于将表作为参数传递给可在SQLServer2008中使用的查询。我对从@custids id中选择id.custid感到困惑。为什么它使用id.custid和@custids idC# C和SQL-sub从表参数中选择,c#,sql-server,tsql,C#,Sql Server,Tsql,下面是一段代码片段,用于将表作为参数传递给可在SQLServer2008中使用的查询。我对从@custids id中选择id.custid感到困惑。为什么它使用id.custid和@custids id private static void datatable_example() { string [] custids = {"ALFKI", "BONAP", "CACTU", "FRANK"}; DataTable custid_list = new DataTable()
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);
}
}
}
子查询中的“id”只是一个别名 与在main FROM子句中使用“C”作为别名并使用“C.CustomerID”的方式相同 子查询也可以是
SELECT custid
FROM @custids