日期:2014-05-18  浏览次数:20465 次

典型sql查询求解,比较难..
Table1
      id                                 CityID
      1                                     1,2,3
      2                                     3,4,5


Table2
      id                                   CityID
      1                                       1
      1                                       2
      1                                       3
      2                                       3
      2                                       4
      2                                       5

----------------
我的解决方法:
create   table   #T(id   int,cityid   varchar(200))
go
insert   into   #T   select   1, '1,2,3 '   union   all   select   2   ,   '2,3,4 '  
go
declare   @T   table   (newid   int   identity(1,1)   primary   key   ,id   int,cityid   varchar(200))
declare   @T2   table   (id   int,cityid   varchar(200))
insert   into   @T   select   id,cityid+ ', '   from   #T   order   by   id   asc
select   id,cityid   from   @T
declare   @i   int
select   @i   =   1
while   @i <=(select   max(newid)   from   @T)
begin
while   (select   charindex( ', ',cityid)   from   @T   where   newid   =   @i)> 0
begin
insert   into   @T2
select   (select   id   from   @T   where   newid   =   @i)   as   id,
(select   substring(cityid,0,(charindex( ', ',cityid)))   from   @T   where   newid   =   @i)   as   cityid
update   @T   set   cityid   =   substring(cityid,charindex( ', ',cityid)+1,len(cityid))   from   @T   where   newid   =   @i
end
select   @i   =   @i   +   1
end
select   *   from   @T2   order   by   id

感觉比较麻烦,期待更好的方法..

------解决方案--------------------
create table #T(id int,cityid varchar(200))
go
insert into #T select 1, '1,2,3 ' union all select 2 , '2,3,4 '
go
declare @sql varchar(8000) set @sql = ' '