Recordset field values return null from SQL server with varchar(MAX) data type

一世执手 提交于 2019-12-13 04:07:24

问题


I have an SQL 2008 server, in the server is a table that has a column with a data type of varchar(MAX). I am trying to import certain columns from this table into Excel 2010 using ADO. Here is an example of the code I am using:

Dim con As Object
Set con = CreateObject("ADODB.Connection")

cmd.CommandText = "SELECT dbo.(Table Name).Name From dbo.(Table)"
cmd.CommandType = 1
con.open
cmd.ActiveConnection = con
Dim rst as Object
set rst = cmd.Execute

ActiveSheet.cells(targetRange.Row, targetRange.Column).CopyFromRecordset rst

The code executes just fine, however because the column Name is set to varchar(MAX) none of the names show up in the worksheet. I know this because I made a copy of the SQL server and changed the data type for the column to varchar(1024) and it works the way it should.

I also tried placing the data in the recordset into the spreadsheet manually but with no luck. So the problem is I can not change the real SQL server.

Is there a command that I can add to the Select statement or a cast that I can use that will convert the varchar(MAX) to a data type that Excel can use, or is there something else I can do so that the data is not null when I read it in?

I have been looking into this problem for a day now with some threads coming close but they are talking about using select on the SQL server with a cast which doesn't work in this case, or in some other program, which doesn't help.


回答1:


ADO apparently doesn't handle VARCHAR(MAX) properly (or how you might expect), something about returning a zero column size as its not defined like it would be for VARCHAR(n).

You answered your own question, as you just needed to cast your column to something with a defined length!

CAST(column AS type)

or in your case

SELECT CAST(dbo.(Table Name).Name AS VARCHAR(1024)) FROM dbo.(Table)


来源:https://stackoverflow.com/questions/15418712/recordset-field-values-return-null-from-sql-server-with-varcharmax-data-type

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