How to fix a collation conflict in a SQL Server query?

后端 未结 5 1961
故里飘歌
故里飘歌 2020-12-09 00:53

I am working on a view, wherein I am using an inner join on two tables which are from two different servers. We are using linked server. When running the query I am getting

5条回答
  •  生来不讨喜
    2020-12-09 01:40

    I resolved a similar issue by wrapping the query in another query...

    Initial query was working find giving individual columns of output, with some of the columns coming from sub queries with Max or Sum function, and other with "distinct" or case substitutions and such.

    I encountered the collation error after attempting to create a single field of output with...

    select
    rtrim(field1)+','+rtrim(field2)+','+...
    

    The query would execute as I wrote it, but the error would occur after saving the sql and reloading it.

    Wound up fixing it with something like...

    select z.field1+','+z.field2+','+... as OUTPUT_REC
    from (select rtrim(field1), rtrim(field2), ... ) z
    

    Some fields are "max" of a subquery, with a case substitution if null and others are date fields, and some are left joins (might be NULL)...in other words, mixed field types. I believe this is the cause of the issue being caused by OS collation and Database collation being slightly different, but by converting all to trimmed strings before the final select, it sorts it out, all in the SQL.

提交回复
热议问题