Joseph Michael
Joseph Michael

Reputation: 167

SQL concatenate two smaller datatypes into one larger datatype

How can I essentially concatenate two smaller datatypes into one larger datatype?

TinyInt(1) = 17 = 0001 0001

TinyInt(2) = 5 = 0000 0101

New SmallInt = TinyInt(1) + TinyInt(2) = 4357 = 0001 0001 0000 0101

I am trying to do this on MSSQL Server 2008 via a stored procedure. The larger value will then be stored in a table.

Upvotes: 0

Views: 69

Answers (3)

Andriy M
Andriy M

Reputation: 77707

There is also a varbinary solution for you. Assuming v1 and v2 are tinyint, you could do this:

CAST(CAST(v1 AS varbinary(1)) + CAST(v2 AS varbinary(1)) AS smallint)

This method directly matches your train of thought but is certainly less elegantly looking than the purely mathematical solution suggested by shawnt00.

Upvotes: 1

shawnt00
shawnt00

Reputation: 17935

You can pack them together by multiplying the first value out of the range of the second value.

v1 * 256 + v2

Upvotes: 1

Becuzz
Becuzz

Reputation: 6857

You can bit shift using the POWER function and then do a bitwise OR (|).

declare @x tinyint
declare @y tinyint

set @x = 17
set @y = 5

declare @z smallint
set @z = @x * power(2, 8) | @y
select @z

Upvotes: 2

Related Questions