根据行中存在的逗号分隔ID获取数据 - SQL

时间:2013-03-16 18:12:39

标签: sql sql-server sql-server-2008 procedure

表1

                HolId
1   Package17   2,1,5
2   Package13   5,4,3

表2

 HolId1
    1   New Years Day   2013-01-01 00:00:00.000
    2   Republic Day    2013-01-26 00:00:00.000
    3   Holi            2013-04-27 00:00:00.000
    4   Memorial Day    2013-05-27 00:00:00.000
    5   US Independence 2013-07-04 00:00:00.000
    7   Labour Day  2013-09-02 00:00:00.000

我想显示如下数据

         HolId    HolId1
Package17   2   2   Republic Day    2013-01-01 00:00:00.000
Package17   1   1   New Years Day   2013-04-27 00:00:00.000
Package17   5   5   US Independence 2013-05-27 00:00:00.000
Package13   5   5   US Independence 2013-07-04 00:00:00.000
Package13   4   4   Memorial Day    2013-05-27 00:00:00.000
Package13   3   3   Holi            2013-04-27 00:00:00.000

我的网格将显示如下,我已经想出

Package17

     Republic Day   2013-01-01 00:00:00.000
    New Years Day   2013-04-27 00:00:00.000
    US Independence 2013-05-27 00:00:00.000

Package13   

    US Independence 2013-07-04 00:00:00.000
    Memorial Day    2013-05-27 00:00:00.000
    Holi            2013-04-27 00:00:00.000

2 个答案:

答案 0 :(得分:4)

这是MySQL的解决方案:

SELECT
T1.Pkg, T2.*
FROM Table2 T2
    JOIN Table1 T1
        ON FIND_IN_SET(T2.HolID1, T1.HolID)

<强> SQL FIDDLE DEMO

这适用于SQL SERVER

SELECT
T1.Pkg, T2.*
FROM Table2 T2
    JOIN Table1 T1
        ON CHARINDEX(CAST(T2.HolID1 as varchar), T1.HolID) > 0

<强> SQL FIDDLE DEMO

答案 1 :(得分:0)

最好将您的桌子去标准化,然后只需一次加入即可获得结果。如果必须使用当前架构。希望以下代码可以帮助您。


declare @tempTable table 
     ( Package_Name varchar(100),
       Holid int
       )
declare @SQLString varchar(max) declare @package_name varchar(100) set @SQLString = '' DECLARE @X XML while @SQLString is not null begin set @SQLString = null select top 1 @package_name=package_name, @SQLString = Holid from Package where package_name not in (select package_name from @tempTable) if @SQLString is null break SET @X = CAST('' + REPLACE(@SQLString, ',', '') + '' AS XML) insert into @tempTable SELECT @package_name, t.value('.', 'INT') FROM @x.nodes('/A') as x(t) end select * from @tempTable select A., B.* from @tempTable A inner join HolID1 B on A.Holid = B.HolID1