Skip to content

SQL: Addition or concatenation

July 26, 2007

select ‘0001’ + 1

What is the result?

Logically, it could be ‘00011’ or 2. It should be ‘00011’ if the + is interpreted as concatenation, , and 2 if the + is iterpreted as addition and (‘0001’ is implicitly cast to a number).

The result is 2. Reminder, addition takes precedence over concatenation.

edit: Upon further examination, the issue isn’t operator precedence but data type precedence.

The data type precedence rules determine which operands get converted to the other.

  • sql_variant (highest)
  • datetime
  • smalldatetime
  • float
  • real
  • decimal
  • money
  • smallmoney
  • bigint
  • int
  • smallint
  • tinyint
  • bit
  • ntext
  • text
  • image
  • timestamp
  • uniqueidentifier
  • nvarchar
  • nchar
  • varchar
  • char
  • varbinary
  • binary (lowest)

Advertisements

From → sql

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: