2012-09-02 32 views
0

我有一个Staging表具有以下的列如何解析SQL表分成多个多到多个表

  • VideoURL
  • 评级
  • 长度
  • 缩略图
  • 标签(逗号-delimited)

视频有多对多的关系ip与标签。我创建了以下新表:

  • 视频
  • 标签
  • VideoTag

如何在临时表中的数据解析成三个新的表?标签表不应包含重复项。另外,在将数据插入新表之前,我需要对数据进行一些格式化,例如需要从长度列中去除所有字母。

+2

我很困惑,请澄清 - 这是纯粹的SQL?在这种情况下,您应该删除ef和c#标签。 –

+0

哎呀,忘记带走了。实际上,我对SQL或实体框架解决方案感兴趣,但EF最终无法接近直接SQL的性能。 – BrazenTongue

回答

1

的两端使用辅助号码表,可以将标签栏分成数行,同时保持它与关联VideoURL:

CREATE TABLE NumberPivot (NumberID INT PRIMARY KEY) 
DECLARE @intLoopCounter INT 
SELECT @intLoopCounter =0 
SET NOCOUNT ON 

WHILE @intLoopCounter <=999 BEGIN 
    INSERT INTO NumberPivot 
    VALUES (@intLoopCounter) 
    SELECT @intLoopCounter = @intLoopCounter +1 
END 
GO 


SELECT 
    ContentPageID, 
    Substring(',' + Tags + ',' 
      , numberID + 1 
      , Charindex(',', ',' + Tags + ',', numberID + 1) - numberid - 1) AS value 
FROM dbo.NumberPivot AS np, 
     Staging AS S 
WHERE numberid <= Len(',' + Tags + ',') - 1 
    AND Substring(',' + Tags + ',', numberID, 1) = ',' 

所以在这里我们填写标签表具有独特的标签:

;WITH X AS (
SELECT 
    VideoURL, 
    Substring(',' + Tags + ',', numberID + 1, Charindex(',', ',' + Tags + ',', numberID + 1) - numberid - 1) AS Tag 
FROM dbo.NumberPivot AS np, 
     Staging AS S 
WHERE numberid          <= Len(',' + Tags + ',') - 1 
    AND Substring(',' + Tags + ',', numberID, 1) = ',' 
) 
INSERT Tag (Tag) 
SELECT DISTINCT Tag FROM X; 

下一页填写视频表:

INSERT Video (VideoURL, Rating, Length, Thumbnail) 
SELECT VideoURL, Rating, Length, Thumbnail 
FROM Staging; 

最后填写VideoTag:

INSERT VideoTag (VideoURL, Tag) 
SELECT 
    VideoURL, 
    Substring(',' + Tags + ',', numberID + 1, Charindex(',', ',' + Tags + ',', numberID + 1) - numberid - 1) AS Tag 
FROM dbo.NumberPivot AS np, 
     Staging AS S 
WHERE numberid          <= Len(',' + Tags + ',') - 1 
    AND Substring(',' + Tags + ',', numberID, 1) = ',' 

了分割字符串使用中的数字表

1

我该怎么做。

  1. 使用此question解析CSV柱为多行另一个表与人工关键旧表链接到新的
  2. 加入另一个产生的人工键两个表(在许多许多加盟表的主键)列创建多对多表
  3. 解决了多对多的关系
1

试试这个,假设videourl视频名称和splitstring功能返回表已经标记名

create table video(...) 
create table tag(...) 
create table videotag(...) 


insert video 
select distinct(maintable.videourl) as videoname 
from maintable 


insert tag 
select distinct(tag.tagname) 
from maintable cross apply SplitString(maintable.tags,',') tag 

insert videotag 
select maintable.videourl as videoname,tag.tagname 
from maintable cross apply SplitString(maintable.tags,',') tag 

如果您自动生成的视频和标签表,然后
而IDS插入到videotag表中得到相关的自动生成的id从
它是主表。

Splitstring功能是从here