2010-11-13 56 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