拆分字符串并从相关数据重建

时间:2012-08-06 23:04:24

标签: tsql

我收到了一个字符串,其中可以包含由代字号123~125~126分隔的多个商品代码 我还有一张表可能可能无法定义父/子关系

tbl_allowed
============
offercode varchar(15)
parent_oc varchar(15)

ex:
offercode = 124
parent_oc = 126

我已经有一个函数将采用分隔的字符串并将其拆分,但我想取字符串,将内容与tbl_allowed中的内容进行比较,并通过替换{{1}中存在的任何值来重新生成它在parent_oc列中,其中包含offercode列中的值。如果不存在已定义的关系,那么只需使用自己。

使用单个商品代码非常简单:

tbl_allowed

但是当我有一个波浪线分隔的字符串时,我遇到了困难。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

这就是我最终做的事情。似乎工作。

    CREATE TABLE #tempoffers(OfferCode varchar(15), NewOfferCode varchar(15))

    INSERT INTO #tempoffers
    SELECT OutParam, null
    FROM dbo.SplitString(@lOfferCode, '~')

    update #tempoffers set NewOfferCode = coalesce(cac.offercode, mb.offerCode)
    from #tempoffers mb
    left outer join tbl_Allowed cac on mb.OfferCode = cac.parent_oc

            -- building the new string
    declare @newOfferCode varchar(5000)
    SELECT @newOfferCode = COALESCE(@newOfferCode + '~', '') + NewOfferCode FROM #tempoffers

    drop table #tempoffers
    SELECT @newOfferCode as OfferCode
相关问题