简体   繁体   English

t-sql字符串串联

[英]t-sql string concatenation

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') 我如何将上述内容转换为字符串(“类型1”,“类型2”,“类型3”)

I want to use the output in my t-sql query with IN clause. 我想在带有IN子句的t-sql查询中使用输出。 Something like select * from TableA where SomeColumn IN ('Type 1','Type 2', Type 3') 类似于从TableA中选择*的内容,其中SomeColumn IN(“类型1”,“类型2”,类型3”)

I used to following to come up with output (type 1, type 2, type 3) 我过去经常提出输出(类型1,类型2,类型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
)

I'm guessing you'd have a where clause on the subselect as well. 我猜你也会在子选择上有一个where子句。

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

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 ). 使用哪种方法取决于对TableA记录和我称为TheOtherTable (带有Type )应用的条件。

Just try it for fun :) 只是尝试好玩:)

declare @s1 varchar(8000)
declare @s2 varchar(8000)

update t
  set  
    @s1 = ISNULL(@s1 + ',', '') + '''' + REPLACE(t.Type, '''', '''''') + ''''
   ,@s2 = 'select * from TableA where Type IN (' + @s1 + ')' 
from TableA t

select @s2

REPLACE(t.Type, '''', '''''') - if field has any apostrophe(s) in field's text, REPLACE will double it. REPLACE(t.Type, '''', '''''') -如果字段的文本中有撇号,REPLACE会将其加倍。 Try to change type1 to typ'e1 or typ''e1 in your table TableA 尝试在表TableA 中将 type1更改为typ'e1typ'e1

I stopped joking... 我开玩笑了...

Try to avoid IN clause and subqueries . 尽量避免使用IN子句和子查询 They work very slow (table scan and so on...)! 它们工作非常慢(表扫​​描等)! Use this: 用这个:

select a.Type 
from TableA a 
  inner join TheOtherTable b 
  on a.Type = b.Type

Whenever you need a quote, double type it 每当您需要报价时,请双击

so ' becomes '' 所以'变成''

so your code becomes 所以你的代码变成

select '(' + STUFF((select ''',''' + Type from TableA for xml path ('')),1,2,'') + ''')'

The above generates 以上产生

('type 1','type 2','type 3')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM