|
 |
|
SQL Server Tips by Burleson |
Handling different data
types
xp_palindrome, srv_willconvert and
srv_convert
This XP takes an input of any data type and returns true if the
input is a palindrome. The returned value is stored in an output
parameter of data type boolean. The XP works with character, numeric
and binary data.
In TSQL all data conversions or castings both implicit and explicit,
convert the value of the data from one data type to another based on
the data representation and not the underlying raw data. For example
an int is stored as four bytes and it can be converted to binary or
CHAR:
DECLARE @i int
SET @i=12345
PRINT CAST(@i as varbinary)
PRINT CAST(@i as varchar)
Output:
0x00003039
12345
The variable @i is stored in four bytes and it can be converted to a
binary data type with the exact same raw data. In contrast,
converting to a varchar changes the length of the data from four to
five bytes as well as modifying its contents. Instead of storing the
value of @i in a 32-bit binary number, the data will be stored in
five bytes, each one with one ASCII character from the value of @i.
Converting from int to real will have no loss of precision due to
rounding, in this example. The two data types are stored in four
bytes of data but the data is quite different, despite representing
the same value:
PRINT CAST(@i as real)
PRINT CAST( CAST(@i as real) as varbinary)
Output:
12345
0x4640E400
Data type conversions by using C++ functions like atoi, atof,
MultiByteToWideChar, etc. are possible in an XP but not necessary.
ODS comes with several functions for simplifying the process of data
type conversions. The two more interesting functions are
srv_willconvert and srv_convert.
The srv_willconvert function returns TRUE if a conversion between
two data types is legal and FALSE otherwise. For example, binary to
real is not accepted. This function is very helpful because it will
reject unacceptable conversions. It is almost always used preceding
a call to srv_convert.
The srv_convert function will convert from one ODS data type to
another. It mirrors the data type conversion functionality, which is
available in TSQL.
int srv_convert (SRV_PROC *
srvproc, int srctype, void * src, DBINT srclen, int desttype, void *
dest, DBINT destlen )
The above book excerpt is from:
Super SQL
Server Systems
Turbocharge Database Performance with C++ External Procedures
ISBN:
0-9761573-2-2
Joseph Gama, P. J. Naughter
http://www.rampant-books.com/book_2005_2_sql_server_external_procedures.htm |