Saving Mssql Auto-Increment Id Problem

here is my "plan" table

  • id : int, auto-increment primary key not null

  • year : datetime

  • deadline : datetime

  • active : tinyint

now when i submit the form it gives me this error


CDbCommand failed to execute the SQL statement: SQLSTATE[23000]: [Microsoft][SQL Server Native Client 11.0][SQL Server]Cannot insert the value NULL into column 'id', table 'Procurement.dbo.plan'; column does not allow nulls. INSERT fails.. The SQL statement executed was: INSERT INTO [dbo].[plan] ([year], [deadline], [active]) VALUES (:yp0, :yp1, :yp2)

my form only includes these input fields :

year

deadline

active


it seems like the instance model has a default value of null.

i tried creating a method like this on my plan model :


public function create()

	{

		$this->id = 0;

	}

so i can use it in my controller like this to avoid null value


public function actionCreate()

	{

		$model=new Plan();


		// Uncomment the following line if AJAX validation is needed

		// $this->performAjaxValidation($model);


		if(isset($_POST['Plan']))

		{

			$model->attributes=$_POST['Plan'];

			$model->create();

			if($model->save())

				$this->redirect(array('view','id'=>$model->id));

		}


		$this->render('create',array(

			'model'=>$model,

		));

	}

i was expecting that mssql will accept and treat 0 (zero) value and generate auto-increment value. but it just accepts the value 0 (zero), so my table row has an id of 0 (zero). and trying to submit the form again will give me an duplicate primary key error.

how can i resolve this? please help

Check the syntax of the table schema.

AFAIR, there’s no AUTO_INCREMENT in MS SQL, it uses ‘identity’ or something. See MSSQL docs for details.

thank you it works. just made a stupid mistake of changing the identity of wrong table and not the plan table. :lol: