国家表Country:
ID  Name
001 中国
002 美国城市表City:
ID  CountryID Name
001 001       北京
002 001       西安
003 002       芝加哥城区表Area
ID CityID Name
001 001   海定

解决方案 »

  1.   

    1,
    create function getstr(@id Nchar(4000))
    returns Nvarchar(4000)
    as 
    begin
    declare @str Nvarchar(2000)
    set @str=N''
    select @str=@str+rtrim(Name)+N' ' from 表
    where left(ID,3)=@id 
    if @str<>N'' 
        set @str=left(@str,len(@str)-1)
    return @str
    endGO
    2,
    select dbo. getstr( left(id,3)) as 名称 from table group by left(id,3)
      

  2.   

    蚂蚁老大
       太感谢了,不过现在还有一个小问题。就是出现一个错误
      “ 列 'tblXzGx.id' 在选择列表中无效,因为该列既不包含在聚合函数中,也不包含在 GROUP BY 子句中。“
      id列定义为VARCHAR(9)
    是不是和这个有关系呢??
      

  3.   

    select dbo. getstr(left(id,3)) as 名称 from table order by left(id,3)--试一试order
      

  4.   

    select dbo. getstr( left(id,3)) as 名称 
        from table 
        group by left(id,3)
        order by left(id,3)
      

  5.   

    楼主,虽然CrazyFor(蚂蚁) 的方法好,但我觉得楼主表的结构不好,wolfAone(30,奋斗成男人) 提出的表结构更好。
      

  6.   


    Create Table ##tmpTB(ID_S Char(3),Name_1 VarChar(20) Null,Name_2 VarChar(20) Null,Name_3 VarChar(20) null)
    Declare @id Char(9),@Name VarChar(20),@SwapName1 VarChar(20),@SwapName2 VarChar(20)
    Declare Cu_A Cursor For Select ID,Name From 表名 Order by ID
    Open Cu_A
    Set @SwapName1=''
    Set @SwapName2=''
    Fetch Cu_A Into @id,@Name
    while @@Fetch_Status=0
    begin
       if Len(@Id)=3
       Begin
          Set @SwapName1=@Id
          Insert Into ##tmpTB values(@ID,@Name,Null,Null)
       end
       if Len(@Id)=6
       begin
         Set @SwapName2=@Id
         if SubString(@id,1,3)=@SwapName1
           UpDate ##tmpTB Set Name_2=@Name where SubString(ID_S,1,3)=@SwapName1
       end
       if Len(@Id)=9
       begin
         if SubString(@id,1,6)=@SwapName2
            UpDate ##tmpTB Set Name_3=@Name where SubString(ID_S,1,3)=@SwapName1
       end
       Fetch Cu_A Into @id,@Name
    end
    Close Cu_A
    Deallocate Cu_A
    Select Name_1,Name_2,Name_3 From ##tmpTB
      

  7.   

    国家表Country:
    ID  Name
    001 中国
    002 美国
    -----------------------------
    select id into #t1 from table where len(id)=3城市表City:
    ID  CountryID Name
    001 001       北京
    002 001       西安
    003 002       芝加哥
    --------------------------------
    select left(id,3) as aaa,right(id,3)as bbb into #t2 from table where len(id)=6城区表Area
    ID CityID Name
    001 001   海定
    -------------------------------------------------
    select left(id,3) as aaa,substring(id,4,3) as bbb,right(id,3) as ccc
    into #t3 from table where len(id)=9
    我觉得是一样的