簡體   English   中英

如何在 SQL Server 中連接

[英]How to concatenate in SQL Server

我的數據庫沒有特定的列,所以我通過 switch 在我的查詢中創建了一個列。 我需要的是將此列與數據庫中的另一列連接起來:

select 
    certificateDuration ,
   'DurationType' = case
                      when certificateDurationType = 0 then 'Day' 
                      when certificateDurationType = 1 then 'Month'
                      when certificateDurationType = 2 then 'Year'
                    end
from 
    Scientific_Certification

要在 SQL Server 中連接字符串,您只需使用+ 運算符即可
請注意,如果子字符串之一為空,則整個連接的字符串也將變為空。 因此,如果您需要結果,即使一個子字符串為空,也請使用COALESCE

select certificateDuration,
       ' DurationType = '+ 
       COALESCE(case
                     when certificateDurationType = 0 then 'Day' 
                     when certificateDurationType = 1 then 'Month'
                     when certificateDurationType = 2 then 'Year'
                     end, '') As DurationType 
from Scientific_Certification

注意:由於您沒有默認行為(由else指定),因此我在您的 case 子句上使用了 coalesce 。 這意味着如果certificateDurationType不是 0、1 或 2,則 case 語句將返回null

您只需要嘗試+運算符或CONCAT函數

  1. +適用於所有 SQL Server 版本

    DurationType = ' + 'some text'
  2. SQL Server 2012 + CONCAT

     CONCAT('DurationType = ', 'some text')

您的查詢應該是這樣的

SELECT certificateDuration
       ,'DurationType = ' + 
       CASE certificateDurationType
           WHEN 0 THEN 'Day'
           WHEN 1 THEN 'Month'
           WHEN 2 THEN 'Year'
       END
FROM Scientific_Certification

您必須嘗試使用​​此 SQL 查詢來聯系列。 在這里,我連接了名為 (name_first, name_middle, name_last) 的用戶表的三列,並將結果放入名為 FULLNAME 的單個列中。

SQL查詢代碼

這是結果的圖像

結果

暫無
暫無

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

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