I have created a database where I use uniqueidentifier as the primary key. I'm trying to run a parametrized query that in the end looks like this. (insert into someTable (uniqueID) Values('76c14693-5475-4224-ba94-7d30c919ac59') (uniqueID is my PK). This insert statement executes without issues when I run it in SQL Server Management Studio, however, it fails when I try to run it from my code.
Error: Cannot insert explicit value for identity column in table 'someTable' when IDENTITY_INSERT is set to OFF.
I have looked this up and there are a lot of suggestions on turning ON the IDENTITY_INSERT but they all use stored procedures. I need to be able to do this using a parametrized query. Or I need a way to get the newly created guid in the database. This seems like something everyone would need at some point. Are there any simple solutions?
PS. I need the ID because I need to add records to other tables using that ID.
EDIT:
Here is the Structure of the table in question
CREATE TABLE [dbo].[someTable]
(
[NewsID] [uniqueidentifier] NOT NULL CONSTRAINT [DF_someTable_NewsID] DEFAULT (newid()),
[ShortTitle] [nvarchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[DateCreated] [datetime] NULL CONSTRAINT [DF_someTable_DateCreated] DEFAULT (getdate()),
CONSTRAINT [PK_cmc_News_1] PRIMARY KEY CLUSTERED (
[NewsID] ASC )WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF
) ON [PRIMARY]
) ON [PRIMARY]
Actually, you must have some other problem, or some other column in you table, because you only would get that error if you have an IDENTITY column in your table, and IDENTITY columns can't be of the datatype uniqueidentifier - are you sure you're inserting into the same table, or you aren't using an ORM tool of some kind that is trying to specify a specific value for an identity column? Perhaps you could script the table definition out and attach it?
EDIT: Adding additional info since the question now includes the schema.
Looks like there is no identity in this particular table, so I'd first check to see if you have any triggers defined on the table in question and see if there is an attempted insert taking place in another table that uses an identity...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With