有没有办法将此查询转换为常规内联SQL

时间:2010-04-19 05:27:52

标签: c# sql-server-2008

我想在不使用存储过程的情况下将此查询转换为常规内联sql

declare @nod hierarchyid
select @nod = DepartmentHierarchyNode
from Organisation
where DepartmentHierarchyNode = 0x6BDA

select * 
from Organisation
where @nod.IsDescendantOf(DepartmentHierarchyNode) = 1

有办法吗?

2 个答案:

答案 0 :(得分:3)

当然,没问题......

using(SqlConnection con = new SqlConnection(......))
{
   string stmt = 
      "declare @nod hierarchyid; " + 
      "select @nod = DepartmentHierarchyNode from Organisation where DepartmentHierarchyNode = 0x6BDA; " + 
      "select * from Organisation where @nod.IsDescendantOf(DepartmentHierarchyNode) = 1";

   using(SqlCommand cmd = new SqlCommand(stmt, con))
   {
      con.Open();
      using(SqlDataReader rdr = cmd.ExecuteReader())
      {
         // here, read your values back
      }
      con.Close();
   }
}

应该这样做。我确实在你的内联SQL查询中看到了多个语句没有任何问题。

答案 1 :(得分:0)

当然,您可以将其转换为单个选择语句,避免使用CTE:

SELECT t1.* 
FROM Organisation t1,
    (SELECT * FROM Organisation 
        WHERE DepartmentHierarchyNode = 0x6BDA) t2
WHERE t1.DepartmentHierarchyNode  = t2 OR
    t2.DepartmentHierarchyNode.IsDescendantOf(t1.DepartmentHierarchyNode) = 1