t-sql 字符串连接 [英] t-sql string concatenation
问题描述
我有一个包含以下列的表格
i have a table that has following column
Type
--------
type 1
type 2
type 3
如何将上面的内容转换为类似 ('type 1', 'type 2', 'type 3') 的字符串
How can i convert the above to a string like ('type 1', 'type 2', 'type 3')
我想在带有 IN 子句的 t-sql 查询中使用输出.类似于 select * from TableA where SomeColumn IN ('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')
我过去常常跟着想出输出(类型 1、类型 2、类型 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:
select * from TableA where SomeColumn IN (
select Type from TheOtherTable
)
我猜你在子选择中也会有一个 where
子句.
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:
select * from TableA a
left outer join TheOtherTable b on a.SomeColumn = b.Type
where b.Type is not null
您使用哪个取决于您对来自 TableA
的记录和我称之为 TheOtherTable
(带有 Type
).
Which you use depends on the criteria you're applying to both the records from TableA
and what I've called TheOtherTable
(the one with Type
).
这篇关于t-sql 字符串连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!