簡體   English   中英

t-sql字符串串聯

[英]t-sql string concatenation

我有一個具有以下列的表

Type
--------
type 1
type 2
type 3

我如何將上述內容轉換為字符串(“類型1”,“類型2”,“類型3”)

我想在帶有IN子句的t-sql查詢中使用輸出。 類似於從TableA中選擇*的內容,其中SomeColumn IN(“類型1”,“類型2”,類型3”)

我過去經常提出輸出(類型1,類型2,類型3)

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

但是不知道如何插入單引號。

通常的方法是使用子選擇:

select * from TableA where SomeColumn IN (
    select Type from TheOtherTable
)

我猜你也會在子選擇上有一個where子句。

根據復雜性,有時您可以使用外部聯接來執行此操作:

select * from TableA a
left outer join TheOtherTable b on a.SomeColumn = b.Type
where b.Type is not null

使用哪種方法取決於對TableA記錄和我稱為TheOtherTable (帶有Type )應用的條件。

只是嘗試好玩:)

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, '''', '''''') -如果字段的文本中有撇號,REPLACE會將其加倍。 嘗試在表TableA 中將 type1更改為typ'e1typ'e1

我開玩笑了...

盡量避免使用IN子句和子查詢 它們工作非常慢(表掃​​描等)! 用這個:

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

每當您需要報價時,請雙擊

所以'變成''

所以你的代碼變成

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

以上產生

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM