Coding Villa Forum
FAQs
Advertisements

SqlException was caught while Inserting Data in a Table in SQL Server 2008.

Iram Online 5/8/2012 12:31:42 PM

Hello Friends!

I am working on an asp.net website. I am trying to insert articles in DB on the basis of articleid. For that purpose i have set articleid as primary key in my database table. I have also set Identity specification. However, after setting Identity specification to yes my data is not inserting in DB. It is throwing an Sqlexception with error message 

"Cannot insert explicit value for identity column in table 'UserArticleDetails2' when IDENTITY_INSERT is set to OFF"

 

Following is its stored procedure.

 

ALTER PROCEDURE [dbo].[Proc_UserArticleDetails_AddNew]

(

@ArticleId INT OUTPUT,

@cat_idl2 INT,

    @title NVARCHAR(50),

    @description NVARCHAR(300),

    @details TEXT,

    @MetaKeywords NVARCHAR(200),

    @Inactive BIT,

    @Userid INT

)

AS

BEGIN

SET @ArticleId = ISNULL((SELECT MAX(@ArticleId) + 1 FROM UserArticleDetails2 WITH (NOLOCK)),1)

IF @ArticleId IS NULL

SET @ArticleId = 1


INSERT INTO [UserArticleDetails2]

           (ArticleId,Userid, cat_idl2, title, description, details,MetaKeywords, Inactive)

     VALUES

           (@ArticleId, @Userid, @cat_idl2, @title, @description, @details,@MetaKeywords, @Inactive)


END

 

Please friends explain its reason and solution. Waiting for your guidance. 

Thanks

 

Share with Friends

Advertisements

Answer

Mehmood Online 5/12/2012 2:40:43 AM

Dear iram ,
We don't need to mentioned the identity column in insert, it manage it itself.

Don't use ArticleID neither in Insert nor in Values and select the identity scope after the insert statement.

If ArticleID will need to pass in stored procedure then remove the identity constraint from table.

If it is an auto incremented number then do it as I mentioned below:
Remember to set the seed and incremented interval.
In other words identity(1,1) , ' ll describe that value of this field will start from one and 'll continue with one interval.
================================
CREATE PROCEDURE My_Insert
    @col1            VARCHAR(20),
    @new_identity    INT    OUTPUT
AS
BEGIN
    SET NOCOUNT ON

    INSERT INTO My_Table (col1)
    VALUES (@col1)

    SELECT @new_identity = SCOPE_IDENTITY()

    SELECT @new_identity AS id

    RETURN
END

Answer

Iram Online 5/19/2012 1:14:41 PM

Thanks Mehmood for the answer. Yes the problem same as you described above. Now I have removed ArticleId from Insert statement and the problem is solved.
Share with Friends

Post reply

 

Enter This Code
Captcha
 

Subscribe

Email me when people reply


Subscribe to the