[SQL Server]Implicit conversion from data type varchar to varbinary(max) is not allowed. Use the CONVERT function to run this query.

Hello,

I am trying to insert a field with CActiveRecord and apparently the field type is a varbinary(max). It’s a SQL server database. What are my options with Yii and dealing with this field type? We don’t control the database so I can’t change the field type to varchar even though it’s only text being inserted into it.

Is there a way in my model to a convert? Something like -

CONVERT(VARBINARY(MAX), $this->comments)

Can that sort of thing be done on the fly with CActiveRecord?

you could setup this in beforeSave of your model like so


public function beforeSave()

	{

		$this->comment = your_php_fn_for_converstion($this->comment);

		return parent::beforeSave();

	}

So I tried something like this -


$comments = hex2bin($this->comments);

$this->comments = $comments;

But I think CActiveRecord is still inserting as a string. I think it needs to somehow insert it as binary.

For anyone else looking to do something like this you can do


protected function beforeSave()

	{

		$this->comments =  new CDbExpression("CONVERT(VARBINARY(MAX), :comments)", array(':comments' => $this->comments));


		return parent::beforeSave();

	}