ColinMac
ColinMac

Reputation: 640

SQL Server 2012 multiple joins technique

I have appended a series of columns (11 of them) to the end my data that each act as a flag.

Here is a sample of these categories: (Notice that multiple flags can appear for a single row!)

cat2    cat3    cat4    cat5    cat6    cat7    cat8    cat9    cat10   cat11   cat12
NULL    1       NULL    NULL       2    NULL    NULL       1    NULL    NULL    NULL
NULL    NULL    NULL    NULL    NULL    NULL       2    NULL    NULL    NULL    NULL
NULL    NULL    NULL       1       1    NULL    NULL    NULL    NULL    NULL    NULL
NULL       1       1    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL
   3    NULL    NULL    NULL    NULL    NULL       2    NULL    NULL    NULL    NULL

I have a separate table that pairs each flag with a description string.

ref_id  category_position   description
------------------------------------------------
1                      2    string description 1
2                      2    string description 2
3                      2    string description 3
1                      3    string description 4
1                      4    string description 5
1                      5    string description 6
1                      6    string description 7
2                      6    string description 8
1                      7    string description 9
1                      8    string description 10
2                      8    string description 11
1                      9    string description 12
1                      10   string description 13
1                      11   string description 14
1                      12   string description 15

I want to somehow join my string description against every category that is not null, so that my categories are 'human readable' and defined.

Here is a possible outcome that would be acceptable to me, based on the first row of sample data (including the header):

cat3  [join description]     cat6  [join description]     cat9  [join description]
   1  string description 4      2  string description 8      1  string description 12

Trouble is - I don't know how to do this multi-part join. I don't want to join 12 times as this seems sloppy and perhaps won't work for the millions of rows I'm operating on.

Upvotes: 0

Views: 50

Answers (1)

S3S
S3S

Reputation: 25152

Here's the function alternative... which isn't going to be faster than doing the joins but is useful in limited use.

create function dbo.returnDesc (@ref_id int)
returns varchar (256)
as
begin
    declare @return varchar(256)

    set @return = (select [description] from yourTable where ref_id = @ref_id)

    return @return
end

Then in use....

select
   ....
   dbo.returnDesc(cat2),
   dbo.returnDesc(cat3),
   dbo.returnDesc(cat4),
   ....
from
    YourMainTable

Upvotes: 1

Related Questions