.net - Cast varchar to byte[] -
get bytes varchar
[word] varchar(600)
problem follow code retrieves 30 bytes.
if [word] longer 30 bytes truncated.
if [word] shorted 30 packed 0s.
how can retrieve actual number of bytes.
yes need bytes of [word].
limit of 5 tags: sql 2008 r2, c#
sqlcommand sqlcmd = sqlcon.createcommand(); system.data.sqltypes.sqlbytes charsb; byte[] charb; int32 id; sqlcmd.commandtext = "select [id], cast(rtrim([word]) binary), [word] " + "from [ftsworddef] (nolock) order [word];"; sqldatareader rdr = sqlcmd.executereader(); while (rdr.read()) { id = rdr.getint32(0); charsb = rdr.getsqlbytes(1); charb = charsb.value; stringbyte1252s.add(new stringbyte1252(id,charb)); } rdr.close(); this works
select top 10000 [id], cast(rtrim([word]) binary(4)), len([word]) [ftsworddef] (nolock) order [word] but cannot pass len([word]) size of binary
varbinary throws same error
following throw error
msg 102, level 15, state 1, line 1 incorrect syntax near '('. msg 319, level 15, state 1, line 2
incorrect syntax near keyword 'with'. if statement common table expression, xmlnamespaces clause or change tracking context clause, previous statement must terminated semicolon.
select top 10000 [id], cast(rtrim([word]) binary( len([word]) )), len([word]) [ftsworddef] (nolock) order [word]
from ms pages: http://msdn.microsoft.com/en-gb/library/ms188362(v=sql.105).aspx
"when n not specified in data definition or variable declaration statement, default length 1. when n not specified cast function, default length 30."
you need specify length in cast avoid default of 30 - if length not known in advance or vary, use varbinary large value size or varbinary(max) - prevent unnecessary padding of value since binary fixed width field.
Comments
Post a Comment