2011-07-27 16 views
0

我有下面的表格。其中有多個名稱正常化sql表格下面的表格

Id AllNames 
1 A,B,C 
2 A,B 
3 X,Y,Z 

我想以下面的標準化方式顯示數據。

Id Names 
1 A 
1 B 
1 C 
2 A 
2 B 
3 X 
3 Y 
3 Z 

任何人都可以幫我解決它。

在此先感謝。

+0

希望查詢拆分Allnames?或者你想要正確的桌子設計? – gbn

+0

分割名稱就足夠了。 我可以改變我的表格結構。 – Shine

+0

看到這篇文章http://stackoverflow.com/questions/314824/t-sql-opposite-to-string-concatenation-how-to-split-string-into-multiple-recor –

回答

1

首先,您需要在互聯網上可以找到的100萬個sql server分割函數之一。

http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=50648

CREATE FUNCTION dbo.Split 
(
    @RowData nvarchar(2000), 
    @SplitOn nvarchar(5) 
) 
RETURNS @RtnValue table 
(
    Id int identity(1,1), 
    Data nvarchar(100) 
) 
AS 
BEGIN 
    Declare @Cnt int 
    Set @Cnt = 1 

    While (Charindex(@SplitOn,@RowData)>0) 
    Begin 
     Insert Into @RtnValue (data) 
     Select 
      Data = ltrim(rtrim(Substring(@RowData,1,Charindex(@SplitOn,@RowData)-1))) 

     Set @RowData = Substring(@RowData,Charindex(@SplitOn,@RowData)+1,len(@RowData)) 
     Set @Cnt = @Cnt + 1 
    End 

    Insert Into @RtnValue (data) 
    Select Data = ltrim(rtrim(@RowData)) 

    Return 
END 

然後,你將需要使用遊標或東西的每一行循環。拆分列然後插入到您選擇的表中。

Declare @denorm table (
id int, 
val varchar(50) 
) 
Declare @denormCol varchar(max),@originalId int  

declare stackCursor CURSOR LOCAL FAST_FORWARD FOR 
select id,allText 
from yourTable 

FETCH NEXT FROM stackCursor 
INTO @denormCol, 
    @originalId 

WHILE @@FETCH_STATUS = 0 
    BEGIN 
     insert into @denorm 
     Select @originalId,Data 
     from dbo.Split(@denormCol,',') 
    END 
CLOSE stackCursor 
DEALLOCATE stackCursor  
0

只是因爲我愛你的選項可以做到這一點的另一種方式是我還沒有看到它這樣做的方式,但對我來說很有意義的CTE。作爲一個方面不是我沒有SQL服務器我,如果你遇到最大的遞歸你可能在第二的所有名稱的情況下,以1添加到字符串的開始/

with recCTE as (
    select id,substring(allNames,0,charindex(',',allNames)) name,substring(allNames,charindex(',',allNames),len(allNames)-charindex(',',allNames)) allNames 
    from yourTable 
    union all 
    select id, 
    case when charindex(',',allNames) >0 then 
    substring(allNames,0,charindex(',',allNames)) name 
    else 
    allNames name 
    end 
    ,case when charindex(',',allNames) >0 then 
    substring(allNames,charindex(',',allNames),len(allNames)-charindex(',',allNames)) allNames 
    else 
    '' 
    end 
    from recCTE 
    where allNames <> '' 
) 

select id,name 
from recCTE