0

I use a closed source commercial application that uses an MS-SQL database. I regularly have to query this database myself for various purposes. This means the table and database design is fixed, and I can't do anything about it at all. I just have to live with it. Now I have two tables with the following layouts (abstracted, not to discredit the software/database designer)

t1: ID (int), att1(varchar), att2(varchar), .... attx(varchar)

t2: ID (int), t1_ids(varchar)

Now the contents of this t1_ids is (shudder) a comma separated list of t1 id's. (for example 12, 456, 43, 675, 54). What I want to do is (you guessed it) join those two tables.

Fortunately for me, these are very small tables, and I don't care about performance in terms of complexity at all (could be O(n^m) as far as I care).

Ideally I would like to make a view that joins these two tables. I don't have any requirements for inserting or updating, just for select statements. What would be the easiest and clearest (in terms of maintainability) way to do this?

Martijn
  • 11,964
  • 12
  • 50
  • 96
  • 1
    possible duplicate of [T-SQL: Opposite to string concatenation - how to split string into multiple records](http://stackoverflow.com/questions/314824/t-sql-opposite-to-string-concatenation-how-to-split-string-into-multiple-recor) – Lucero Dec 20 '10 at 11:41

2 Answers2

1

To get the first and last too use this:

select * 
from t1 
    join t2 on '%,' + t1.ID + ',%' like ',' + T2.t1_ids + ','

It doesn't matter if T2.t1_ids start or end with . The valid values are enclosed by commas.

bernd_k
  • 11,558
  • 7
  • 45
  • 64
0

EDIT: I realised after posting this answer the PARSENAME function can only return one part of the parsed string, so it's not a useful as I thought it would be in your situation.

Searching SO for alternative solutions I came across an interesting answer to this question: Split String in SQL

If you can add triggers to your database then you could call the split string on INSERT, UPDATE and DELETE to maintain another table with the id's separated as rows. Then you can create your view using that table.

I know you said you don't mind about the speed of the query but at least that way you are not parsing all the strings every time you query the data.

Community
  • 1
  • 1
Tony
  • 9,672
  • 3
  • 47
  • 75