从表

时间:2018-06-03 06:50:35

标签: sql sql-server database

我有一个带参考值的表和另一个表作为选定的参考值。在此表中,所选参考值以逗号分隔。如何从逗号分隔值中获取单个值?

CREATE TABLE [DBO].[TBL_REFERENCE] 
(
    /* REFERENCE TABLE */
     REF_ID BIGINT IDENTITY(1, 1) NOT NULL
    ,REF_NUMBER INT NOT NULL
    ,REF_NAME NVARCHAR(20)
    ,REF_VALUE NVARCHAR(25)
    ,CONSTRAINT PK_REFERENCE PRIMARY KEY (REF_ID)
)

INSERT INTO TBL_REFERENCE (ref_number, ref_name, ref_value) 
VALUES (1, 'communication', 'mobile'),
       (1, 'communication', 'laptop'),
       (1, 'communication', 'PDA'),
       (1, 'communication', 'tabs'),
       (1, 'communication', 'iphone'),
       (1, 'communication', 'smart phone'),
       (1, 'communication', 'others');

另一张表

CREATE TABLE [DBO].[TBL_FACILITY] 
(
    /* FACILITY TABLE */
     FACILITY_ID BIGINT IDENTITY(1, 1) NOT NULL
    ,FAMILY_HEAD_ID BIGINT NOT NULL
    ,FACILITY_SELECTED INT --- REF_NAME
    ,FACILITY_USED NVARCHAR(25) --- ref_value
    ,CONSTRAINT PK_FACILITY PRIMARY KEY (FACILITY_ID)
    )   

INSERT INTO TBL_FACILITY (FAMILY_HEAD_ID, FACILITY_SELECTED, FACILITY_USED) 
VALUES (121, 1, '2,6'), (122, 1, '5'), (123, 1, '5,6');

最终结果的格式:

121 communication laptop
121 communication smart phone
122 communication iphone
123 communication iphone
123 communication smart phone

我怎样才能得到这个结果?

1 个答案:

答案 0 :(得分:0)

假设tbl_reference.ref_number和{{1}作为标识列,SUBSTRING列的值按向下顺序排列为1,2,3,4,5,6,7 }字符串运算符,您可以使用以下SQL:

CHARINDEX

SQL Fiddle Demo