sqlserver字段中保存xml格式内容时报错的问题

时间:2021-11-26 18:03:53

如果你数据表里保存的是xml数据:


such as:


<order version="1.0" orderid="123669425" orderid_parent="" shopid="" unionName="doumai" userid="102138995730010" is_newbuyer="" input_type="get" buydate="2013-09-25 19:06:54" paydate="" total_price="23.40" total_commission="" username="" tracking_code="" fld="" fanli="" point="" consume_status="" consume_time="" platform="" consumed="" pay_status="" pay_type="" order_status="" deli_name="" deli_no="" complete="0" status_sign=""><products><product product_id="0" total_price="23.40" total_num="1" commission_id="" commission="0" fanli="" point="" product_title="" category_id="" category_title="" product_url="" consume_status="" status_sign=""/></products></order>


那么使用php调用mysql时报错:


Unicode data in a Unicode-only collation or ntext data cannot be sent to clients using DB-Library (such as ISQL) or ODBC version 3.7 or earlier.


原因可以看这里:

http://hi.baidu.com/tylzyoudi/item/bd087657d519979408be177c


大概意思是,这是因为我们的pymssql使用早期的ODBC函数集来获取数据。后来微软才引入了ntext和nvarchar类型,但Microsoft并没有更新他们的 C-library,所以就没办法支持了。建议:将ntext修改为nvarchar或text.

显然,这不是个好的解决方法,那么是否就没有其他办法了呢?

还好,不用绝望,既然不支持ntext但支持text,那么我们只需要在输出时将ntext转换为text就好了,方法很简单:

SELECT cast ( field_name AS TEXT ) AS field_name


之后我们就cast(orderxml as TEXT),发现依旧报错:


Explicit conversion from data type xml to text is not allowed. 


然后我们看这里:

http://www.php.net/manual/zh/ref.mssql.php


发现是要这样:


4. So you cannot read the VARCHAR nor the XML, and you cannot transform the XML into TEXT. In order to finally read that XML field-type, you may use this trick :

"SELECT CAST(CAST([xmlfield] AS VARCHAR(8000)) AS TEXT) FROM [table]"


所以我们这样:

select cast(cast(orderxml as varchar(8000)) as TEXT) as orderxml


终于可以解决问题了~~