Sqlsrv :: Guid :: Conversion Failed When Converting From A Character String To Uniqueidentifier

Hi, im new in yii, and i am tryin to use an existing sql server database with yii. I could create the models,controllers,and views but, when i try to save a new object with a uniqueidentifier type pk, the system says:

Conversion failed when converting from a character string to uniqueidentifier

I did validate an example : {33EF43BE-1D79-0148-831F-462752D033CD} and is ok.

This is part of my Model’s code:

public function beforeSave() {

    if (!$this->ContactoGUID) {

        $this->ContactoGUID = $this->guid();

        //$this->owner->guid = $guid->guid;



function guid(){

	if (function_exists('com_create_guid')){

        return com_create_guid();


        mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.

        $charid = strtoupper(md5(uniqid(rand(), true)));

        $hyphen = chr(45);// "-"

        $uuid = chr(123)// "{"

            .substr(&#036;charid, 0, <img src='http://www.yiiframework.com/forum/public/style_emoticons/default/cool.gif' class='bbc_emoticon' alt='8)' />.&#036;hyphen

            .substr(&#036;charid, 8, 4).&#036;hyphen

            .substr(&#036;charid,12, 4).&#036;hyphen

            .substr(&#036;charid,16, 4).&#036;hyphen


            .chr(125);// &quot;}&quot;

        return &#036;uuid;



Can anybody give me a hand with this?

Thanks in advance,

Best Regards


  1. when overriding beforeSave() you have to call the parent implementation and you need to return the result of that.

    return parent::beforeSave();

  2. In which line of the code does the error occur?

Hi CeBe,

did you mean this:

public function beforeSave() {


	    if (&#33;&#036;this-&gt;ContactoGUID) {


	        &#036;this-&gt;ContactoGUID = &#036;this-&gt;guid();




	    return true;



        return false;




The error still there. C:\wamp\www\yii-1.1.13\framework\db\CDbCommand.php(357)

throw new CDbException(Yii::t(‘yii’,‘CDbCommand failed to execute the SQL statement: {error}’,

and happend when i executed


Thanks for your repply



Solved !!

i just change the property type from String to uniqueidentifier and then i make a validation in beforeSave().

Thanks anyway CeBe