2010-11-13 40 views
0

我有顺序表如何写分割两行的查询?

OrderId OrderStatusId CurrencyId  PromotionCode 
------------------------------------------------------ 
    137   5   1    123a-123d 
    138   5   1    123a-123d-234c 

我要拆分的PromotionCode列如下:

结果:

OrderId OrderStatusId CurrencyId PromotionCode 
----------------------------------------------------- 
    137    5    1    123a 
    137    5    1    123d 
    138    5    1    123a 
    138    5    1    123d 
    138    5    1    234c 

请帮我...

是有可能做...任何方式plz帮助我尽可能....

+0

如果您发布代码,XML或固定宽度的表格及类似内容,请**在文本编辑器中突出显示这些行,然后单击编辑器工具栏上的“代码”按钮(101 010)以精确地格式化并语法突出显示它! – 2010-11-13 11:35:39

回答

2

如果促销代码总是4个字符长,最简单的方法可能是一个联盟:

select id, substring(code,1,4) 
from YourTable 
where LEN(code) >= 4 
union all 
select id, substring(code,6,4) 
from YourTable 
where LEN(code) >= 9 
union all 
select id, substring(code,11,4) 
from YourTable 
where LEN(code) >= 14 
<etc> 

对于更灵活的解决方案,看看各种Split functions之一。在数据库中创建此功能后,您可以调用它:

select t.id, s.items 
from YourTable t 
cross apply 
     dbo.Split(t.code,'-') s 

这两个查询都会根据您的答案中的要求生成结果。

+0

你能解释如何使用拆分功能来做同样的结果吗我创建....帮助我很快 – jay 2010-11-13 17:11:19

+0

@jay:示例使用Split添加到答案 – Andomar 2010-11-14 00:29:42