将单列Value分隔为SQL中的多个列

时间:2015-01-23 13:39:12

标签: sql sql-server-2012

我有以下格式的表格,

MENUACTION         VALUE

ReceivedDetails    ACCOUNTNO v="3275402GBP"
ReceivedDetails    AGR1 
ReceivedDetails    AGR2 

我需要以下格式的表格

MENUACTION         VALUE                       CONTROLID      DATAVALUE      

ReceivedDetails    ACCOUNTNO v="3275402GBP"    ACCOUNTNO      3275402GBP
ReceivedDetails    AGR1                        AGR1
ReceivedDetails    AGR2                        AGR2

注意:Value Column中的记录是动态的,我们需要将value列中的标记分成两个不同的列(ControlID,DataValue)

你能帮忙吗?提前谢谢。

1 个答案:

答案 0 :(得分:0)

步骤1:更改表以添加DATAVALUE列 第2步:运行此

update table [tablename]
set Value = left(
              -- The Right below gets 3275402GBP"
              Right(VALUE, len(Value) - charindex('v=', Value) - 2),
              -- and the left gets it again to get it's length - 1
              -- leaving 3275402GBP
              Len(Right(VALUE, len(Value) - charindex('v=', Value) - 2) - 1
                 )
-- exclude any without a 'v=' to avoid invalid substrings
where charindex('v=', Value) > 0