SQL JOIN on varchar with special characters and leading zeros

半城伤御伤魂 提交于 2020-01-15 10:38:08

问题


I have a problem with join on varchar column.

I'm going to update SQL data from Excel data by product code but Twr_Kod is varchar and it is the only way to join with Excel data.

There is also problem with convert to varchar when there are leading zeros.

select CDN.Towary.Twr_Kod, excel.Twr_Kod 
from CDN.Towary 
left join openrowset('Microsoft.ACE.OLEDB.12.0', 
                     Excel 8.0;Database=C:\excel\towary.xlsx;',
                     'select * from [Arkusz1$]') excel 
                  on cast(CDN.Towary.Twr_Kod as varchar) = cast(excel.Twr_Kod as varchar)

I know it is not a good solution to join on varchar column but it's necessary so please help why cast is not converting.


回答1:


The problem is because your excel column contains mixed data types. When importing csv file or excel files with mixed data types column it will replace non dominant types by null. (Using Oledb or Ace.Oledb)

Workaround

Add IMEX=1; to your openrowset connectionstring and add a dummy first row containning text values

Follow my answer at Import error using Openrowset to get more details



来源:https://stackoverflow.com/questions/42551209/sql-join-on-varchar-with-special-characters-and-leading-zeros

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!