i have a table that has following column
Type
--------
type 1
type 2
type 3
How can i convert the above to a string like ('type 1', 'type 2', 'type 3')
I want to use the output in my t-sql query with IN clause. Something like select * from TableA where SomeColumn IN ('Type 1','Type 2', Type 3')
I used to following to come up with output (type 1, type 2, type 3)
select '(' + STUFF((select ', ' + Type from TableA for xml path ('')),1,2,'') + ')'
But dont know how to insert the single quotes.
The usual way is with a subselect:
I'm guessing you'd have a
where
clause on the subselect as well.Depending on complexity, sometimes you do this with outer joins instead:
Which you use depends on the criteria you're applying to both the records from
TableA
and what I've calledTheOtherTable
(the one withType
).Just try it for fun :)
REPLACE(t.Type, '''', '''''')
- if field has any apostrophe(s) in field's text, REPLACE will double it. Try to change type1 to typ'e1 or typ''e1 in your table TableAI stopped joking...
Try to avoid IN clause and subqueries. They work very slow (table scan and so on...)! Use this:
Whenever you need a quote, double type it
so ' becomes ''
so your code becomes
The above generates