DevPinoy.org
A Filipino Developers Community
Attention: Site upgrade failed last night. Will resume updates this weekend. Thanks!- Keith

Datatype Precedence in SQL Server

Wasn't really familiar with this feature of SQL Server until today.

I have a 4-character field (BidTypeID) in SQL server which actually contains integers (pardon the design issues here people) which i have configured as flaggable enumerations in C#.  My stored procedure filtering looks somewhat like this (BidTypeAccess is of type integer):

   WHERE (A.BidTypeID & B.BidTypeAccess > 0)

I was revising some of my stored procs this afternoon when I bumped into some of my old SPs with an explicit conversion of the said field to an integer before doing the masking.

   WHERE (CAST(A.BidTypeID AS INTEGER) & B.BidTypeAccess > 0)

I have been programming in .NET for two years and the code above was a result of being exposed mainly to a strongly-typed language.  Wondering why both codes worked, I posted a query at the public sqlserver newsgroups where I encountered about DataType Precedence and consulted SQL BOL.  Basically, SQL server does an implicit conversion of the operands before performing an operation.  In this case, the operand of the lower precedence, a CHAR(4), is converted to the data type of the operand with the higher precedence, an INTEGER, which is my desired result.

A responder quoted it being breakable specially for future release and service packs of SQL Server and a feature that one shouldn't really rely upon, STRONGLY AGREE!

FROM BOL:
This is the precedence order for the Microsoft® SQL Server™ 2000 data types:

  • 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)

Posted Nov 08 2005, 10:37 PM by jokiz
Filed under: ,

Comments

Mike wrote re: Datatype Precedence in SQL Server
on 11-23-2006 8:50 AM

How would one go about changing the precedence? The reason why I'm asking is because I have a developer machine here that isn't recognizing the comparison between nvarchar(38) and uniqueidentifier without having  completed a cast or convert of the uniqueidentifier first. Although on the rest of the developers machines it works fine without doing any cast or convert. If you have any idea's I would be very happy to hear them.

Thanks,

Mike

Bonski's Box wrote Sql Server Data Type Precedence : Redux
on 04-17-2007 6:11 AM

Previously jokiz bloged about this one , I'd like to add further. The same issue cropped up again in

Add a Comment

(required)  
(optional)
(required)  
Remember Me?

Enter the numbers above:

Copyright DevPinoy 2005-2008
Powered by Community Server (Commercial Edition), by Telligent Systems