開始使用免費開始

串接資料

在 SQL Server 中,經常需要把多個部分組合成一個字串。你可能需要把不同欄位的資訊組合起來,並將整體結果送到其他應用程式。 在這個練習中,你會熟悉各種串接資料的方式。

你將建立一段類似這樣的訊息:「Chocolate with beans from Belize has a cocoa percentage of 0.6400」。

這個句子是把兩個字串變數與 ratings 資料表中的 bean_origincocoa_percent 欄位資料串接而成。

為了限制結果數量,查詢只會選取公司為「Ambrosia」且 bean_type 不是未知的列。

本練習屬於課程

SQL Server 的資料操作函式

檢視課程

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

DECLARE @string1 NVARCHAR(100) = 'Chocolate with beans from';
DECLARE @string2 NVARCHAR(100) = 'has a cocoa percentage of';

SELECT 
	bean_type,
	bean_origin,
	cocoa_percent,
	-- Create a message by concatenating values with "+"
	@string1 ___ ' ' ___ bean_origin ___ ___ + @string2 + ' ' + CAST(___ AS nvarchar) AS message1
FROM ratings
WHERE 
	company = 'Ambrosia' 
	AND bean_type <> 'Unknown';
編輯並執行程式碼