Home Forums SQL Server 7,2000 T-SQL How to Convert nx1 dimension table to 1x1 dimension table RE: How to Convert nx1 dimension table to 1x1 dimension table

  • Hi!

    Try this, without cursors.

    Regards,

    Liliana.

    SELECT TOP 100 n = IDENTITY(INT, 1, 1) INTO #Numbers

    FROM

    sysobjects a1

    CROSS JOIN

    sysobjects a2

    CROSS JOIN

    sysobjects a3

    DECLARE @tblVariable table (Roles varchar(2000))

    insert into @tblVariable VALUES('Role1,Role2,')

    insert into @tblVariable VALUES('Role1,Role3,')

    insert into @tblVariable VALUES('Role1,Role4,')

    insert into @tblVariable VALUES('Role2,Role5,')

    insert into @tblVariable VALUES('Role6,Role1,')

    insert into @tblVariable VALUES('Role7,')

    insert into @tblVariable VALUES('Role8,')

    DECLARE @tblRolesInSingleColumn TABLE(RoleId VARCHAR(8000))

    INSERT @tblRolesInSingleColumn

    SELECT DISTINCT

    SUBSTRING (t.Roles + ',', N.n, CHARINDEX (',', t.Roles + ',', N.n) - N.n) as RoleId

    FROM @tblVariable t

    CROSS JOIN #Numbers N

    WHERE SUBSTRING (t.Roles, N.n - 1, 1) = ',' OR N.n = 1

    ORDER BY 1

    DECLARE @Result varchar(8000)

    SET @Result = ''

    SELECT @Result = @Result + CASE WHEN LEN(@Result)>0 THEN ', ' ELSE '' END + RoleId

    FROM (SELECT DISTINCT RoleId FROM @tblRolesInSingleColumn)Roles

    SELECT @Result RolesIds

    GO