Home Forums Programming General Different behaviour of SQL Server when setting varchar size RE: Different behaviour of SQL Server when setting varchar size

  • Query is something like:

    declare @p1 varchar(4), @p2 varchar(6)

    set @p1 = '%ZH%'

    set @p2 = '%8434%'

    select * from table1 o left join table2 t on o.x=t.x

    where o.canton like @p1 and o.postcode like @p2 and ...

    If I drop (4) or (6) from above query, it outputs result rows. With both set, it does not.

    After a long day I found the solution.

    And I'm ashamed to tell, but the SQL Server must behave like this, since the query is not the same: What I was not aware: If you do not set the size of a varchar parameter, SQL Server defaults to varchar(1). Since in the query the two parameters affected by the size problem were like '%8434%' or like '%ZH%', this default has set the parameter value to '%', which is true for any string and therefore the query had results. In the other way, if I set the varcharsize or if it was set by .NET, the value of the parameter has been '%8434%' and then the output of no result rows simply was correct. I assumed it to be wrong since my query did return values... :unsure: Letting away a join returned results because some restricting where clauses got removed by removing the join.

    So sorry for troubling, but I really learned something out of that and I think some of you will too 😉 I'm glad having found a forum post somewhere deep in the net of a user pointing to the fact of default size 1 and wondering, where this strange default of 1 comes from...

    Cheers, Chris