I have the following tables in a SQL server Database:
[ANIMALS] [COLORS]
ID | NAME ID | NAME
1 Cow 1 Blue
2 Chicken 2 Red
3 Pig 3 Green
4 T-Rex 4 Pink
5 Orange
[RELATIONSHIPS]
ANIMAL ID | COLOR ID
1 3
1 2
1 5
2 1
3 1
3 4
4 1
4 2
4 5
I am trying to write a SQL query that will return the the list of animals along with each of their respective colors. The goal I am attempting to achieve will look like the following:
ANIMAL NAME COLORS
Cow Green/ Red / Orange
Chicken Blue
Pig Blue/ Pink
T-Rex Blue/ Red/ Orange
I already have a user defined function that will create the delimited string (“color/ color/ etc.”) called udf_Delimit_Colors(@animalID) — @animalID is the only parameter within that UDF.
I can return only one row by passing in an animalID and am now stumped as to how I would go about achieving my goal without passing in any ID.
The delimited SQL Query can be found at the following link:
https://sites.google.com/site/sqlblindman/creatingcomma-delimitedstrings
+rep to the person that wrote it.
I am still working on it too so if i figure it out I will post the answer.
Thanks in advance for your input.
Based on your syntax above, I am assuming SQL Server as the database. You can concatenate the string the following ways:
See SQL Fiddle with Demo
Or:
See SQL Fiddle with Demo
The result is: