2010-04-19 70 views
0

我想谈谈这个查询到正规内联SQL,而无需使用存储过程有没有办法把这个查询到正规内联SQL

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

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

有没有办法做到这一点?

回答

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查询中,我没有发现有多个语句出现问题,真的。

+0

究竟发生了什么。所以基本上它几乎是一样的东西呢?在问这个问题之前我应该​​检查一下。我感谢您的帮助。 – Luke101 2010-04-19 05:37:25

+0

我不完全确定,但我想他可能一直在问怎么参数化'hierarchyid',这涉及到使用'SqlHierarchyId'类(我认为)。请注意,整件事情没有什么意义,因为他只是选择了他在第一个查询中已经存在的相同的层次结构ID ......整个上半年似乎是多余的。 – Aaronaught 2010-04-19 05:37:36

+0

@Aaronaught:好吧,他可以使用“Microsoft.SqlServer.Types”程序集中的“SqlHierarchyId”类型,并以某种方式为该参数提供有效值 – 2010-04-19 05:49:54

0

当然,你可以把它变成一个单一的SELECT语句,避免了CTE:

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