Mahendra Dhaker
Mahendra Dhaker

Reputation: 43

Get actual value of a variable in another variable

For example, in below code, I want to set @XYZ with value of @ABC and value of @DEF i.e. @XYZ should be PQRSTU.

DECLARE @ABC VARCHAR(MAX)='PQR',
@DEF VARCHAR(MAX)='STU',
@XYZ VARCHAR(MAX);

Upvotes: 0

Views: 549

Answers (2)

Venkataraman R
Venkataraman R

Reputation: 12959

If you meant concatenation, you can use

DECLARE @ABC VARCHAR(MAX)='PQR',
@DEF VARCHAR(MAX)='STU',
@XYZ VARCHAR(MAX);

SET @XYZ = CONCAT(@ABC,@DEF) 
--or 
SET @XYZ = @ABC + @DEF
+--------+
| PQRSTU |
+--------+

The advantage of CONCAT is, if the value of the variable is null also, it will return empty string of VARCHAR(1) for that. So, your concatenation will be successful

SET @DEF = NULL

SET @XYZ = CONCAT(@ABC,@DEF)
SELECT @XYZ
+--------+
| PQR    |
+--------+

If you want to set value for a variable, you can do two ways:

SET  @xyz = value -- ANSI standard. works across RDBMS systems
SELECT @XYZ = value

Upvotes: 1

Michał Turczyn
Michał Turczyn

Reputation: 37347

Just use select or set keyword:

-- both are equivalent
SELECT @XYZ = @ABC + @DEF;
SET @XYZ = @ABC + @DEF;

Upvotes: 1

Related Questions