如何在下拉列表中显示分层数据

时间:2010-03-21 21:50:46

标签: .net asp.net sql sql-server

我在SQL Server 2005中有一个表。

alt text http://www.techpint.com/sites/default/files/images/table.JPG

我想在维护相同层次结构的下拉列表中显示所有域名。即

  


  工程
  --civil
  --Mechanical
  医疗
  --Dental
  ----腔
  --MBBS

我需要根据域级别附加' - '。是否可以使用SQL查询。 或者我可以使用任何其他控件来显示此数据。

3 个答案:

答案 0 :(得分:2)

在SQL Server 2005及更高版本中,您可以使用递归CTE(基于this article的示例):

DECLARE @t AS TABLE (domainid INT NOT NULL, domainname VARCHAR(25) NOT NULL, parentdomainid INT NULL);
INSERT INTO @t VALUES (1, 'Law', NULL);
INSERT INTO @t VALUES (3, 'Engineering', NULL);
INSERT INTO @t VALUES (4, 'Medical', NULL);
INSERT INTO @t VALUES (6, 'Civil', 3);
INSERT INTO @t VALUES (7, 'Mechanical', 3);
INSERT INTO @t VALUES (8, 'Dental', 4);
INSERT INTO @t VALUES (9, 'MBBS', 4);
INSERT INTO @t VALUES (12, 'Cavity', 8);

-- SELECT * FROM @t;

WITH CTE(domainid, parentdomainid, domainname, Depth, SortCol)
            AS
            (
              SELECT domainid, parentdomainid, domainname, 0, CAST(domainid AS varbinary(max))
              FROM @t
              WHERE parentdomainid IS NULL
              UNION ALL
              SELECT d.domainid, d.parentdomainid, d.domainname, p.Depth + 1,
                        CAST(SortCol + CAST(d.domainid AS binary(4)) AS varbinary(max))
              FROM @t AS d
                        JOIN CTE AS p
                          ON d.parentdomainid = p.domainid
            )
            SELECT domainid, parentdomainid, domainname, Depth, REPLICATE('--', Depth) + domainname as displayname
            FROM CTE
            ORDER BY SortCol;

答案 1 :(得分:1)

1)你需要编写一个查询来选择所有节点的级别(名称,级别) 2)将级别转换为“ - ”的数字并与名称字符串

连接

选择DomainID,Level

的查询(我知道WITH)
CREATE PROCEDURE [GetDomainTree]
(
@topDomainID int
) with encryption
AS
BEGIN
DECLARE @level int
DECLARE @count int

DECLARE @tempTable TABLE (DomainID int, [Level] int)

INSERT INTO @tempTable
(DomainID, [Level])
VALUES
(@topDomainID, 0)
SET @count = 1
SET @level = 0
WHILE @count > 0
 BEGIN
  INSERT INTO @tempTable
  (DomainID, [Level] )
  (
   SELECT DomainsRealTable.DomainID,
       @level + 1,
     @topDomainID
   FROM  @tempTable domains, DomainsRealTable
   WHERE domains.[Level] = @level
      AND DomainsRealTable.ParentDomainID = domains.DomainID
  )
  SELECT @count = COUNT(*)
  FROM   @tempTable
  WHERE  [Level] = @level + 1
  SET @level = @level + 1
 END
SELECT *
FROM   @tempTable
ORDER BY [Level]
END

现在,你可以编写一个sql函数,它将获取int参数(level)并返回nvarchar' - '* Level并组合两个查询以获得你想要的结果

答案 2 :(得分:0)

你也可以用代码

写出来

psudo代码,你明白了

function createlist(parent_id, indent)
{
  if parent_id is null
  {
    select children_name, children_id from table where parent is null
  }
  else
  {
    indent += "--";
    select children_name, children_id from table where parent = parent_id
  }

  foreach result
  {
    write option value="children_id" +indent+children_name+ /option
    createlist(children_id, indent)
  }
}

createlist(null, "");

regardes

詹姆斯林(guanfenglin@gmail.com)