Explain Codes LogoExplain Codes Logo

Printing integer variable and string on same line in SQL

sql
data-type-compatibility
sql-server
variable-declaration
Anton ShumikhinbyAnton Shumikhin·Mar 3, 2025
TLDR

To display an integer and string together in a query, concatenate them. The function or casting ensures compatibility across data types.

MySQL/PostgreSQL:

SELECT CONCAT('Text ', your_integer) FROM your_table;

SQL Server:

SELECT 'Text ' + CAST(your_integer AS VARCHAR) FROM your_table;

Replace Text with your string, your_integer with your integer column, and your_table with your table name.

Approaches to integer-to-string conversion

Using CAST or CONVERT

In SQL Server, when mixing types, CAST or CONVERT can be your best mates:

DECLARE @intValue INT = 10; PRINT 'The value is: ' + CAST(@intValue AS VARCHAR);

Remember, SQL's about as forgiving with types as a grumpy cat with a cucumber. 🐱‍👤🥒

CONCAT - auto-magic conversion

SQL Server 2012+ has CONCAT, auto-magically converting non-string data types:

DECLARE @intValue INT = 10; PRINT CONCAT('The value is: ', @intValue);

It's SQL's personal assistant for concat tasks. "Thank you, JARVIS."

RAISERROR for formatted output

For console.log() fans, SQL Server's RAISERROR (with NOWAIT option) prints formatted messages:

DECLARE @intValue INT = 10; RAISERROR ('The value is: %d', 0, 1, @intValue) WITH NOWAIT;

"Console log spotted in SQL. Javascript dev's secret identity is no longer secret."

Variables and data types handling

Declaring and Initializing Variables

Using DECLARE keyword, initialize the variable:

DECLARE @count INT; SET @count = 100; PRINT CONCAT('Item count: ', @count);

"SQL Server: Name it, set it, print it."

Data-type compatibility is crucial!

Trying to combine an integer with a string without conversion? Not on SQL Server's watch:

SELECT 'The value is ' + @intValue; -- Incorrect, potential error SELECT 'The value is ' + CAST(@intValue AS VARCHAR); -- Correct

"A SQL Server never forgets... a type."

The importance of operator precedence

Remember your math classes: operators have precedence.

SELECT 'Value: ' + 1 + 2; -- Incorrect, equals error due to mathematical attempt SELECT 'Value: ' + CAST(1 AS VARCHAR) + CAST(2 AS VARCHAR); -- Correct

"SQL Server: Successfully making school math problems relevant again."