Concatenating data
Assembling a string from parts is done quite often in SQL Server. You may need to put together information from different columns and send the result as a whole to different applications. In this exercise, you will get familiar with the different options for concatenating data.
You will create a message similar to this one: "Chocolate with beans from Belize has a cocoa percentage of 0.6400".
The sentence is created by concatenating two string variables with data from the columns bean_origin
and cocoa_percent
, from the ratings
table.
For restricting the number of results, the query will select only values for the company called "Ambrosia" and bean_type
is not unknown.
This exercise is part of the course
Functions for Manipulating Data in SQL Server
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
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';