I'm performing a cascading insert in a SQL Server stored procedure. Then I pass the SCOPE_IDENTITY from the ID of the first table insert to the second table.
But during executing the stored procedure I get a NULL value for the SCOPE_IDENTITY:
Msg 515, Level 16, State 2, Procedure InsertDDM_UserProfile, Line 43
Cannot insert the value NULL into column 'Filter', table '.....dbo.DDM_Dashboard'; column does not allow nulls. INSERT fails.
Question: why does the stored procedure return a null ID using SCOPE_IDENTITY?
This is the stored procedure I've drafted. FK constraints have already been set up for the tables:
ALTER PROCEDURE [dbo].[InsertDDM_UserProfile]
#p_email VARCHAR(100),
#p_dashboardName VARCHAR(100),
AS
BEGIN
INSERT INTO [dbo].[DDM_User] ([Email])
VALUES (#p_email)
INSERT INTO [dbo].[DDM_Dashboard] ([Dashboard_Name], [DDM_USER_ID])
VALUES (#p_dashboardName, SCOPE_IDENTITY())
END
And below are the two table's structure:
DDM_User-
CREATE TABLE [dbo].[DDM_User]
(
[ID] [int] IDENTITY(1,1) NOT NULL,
[Email] [varchar](80) NOT NULL,
CONSTRAINT [PK_DDMUser]
PRIMARY KEY CLUSTERED ([ID] ASC)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
DDM_Dashboard:
CREATE TABLE [dbo].[DDM_Dashboard]
(
[ID] [int] IDENTITY(1,1) NOT NULL,
[Dashboard_Name] [varchar](100) NOT NULL,
[DDM_USER_ID] [int] NOT NULL,
CONSTRAINT [PK_DDMDashboard]
PRIMARY KEY CLUSTERED ([ID] ASC)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[DDM_Dashboard] WITH NOCHECK
ADD CONSTRAINT [FK_DDMDashboard_DDMUser]
FOREIGN KEY([DDM_USER_ID]) REFERENCES [dbo].[DDM_User] ([ID])
GO
ALTER TABLE [dbo].[DDM_Dashboard] CHECK CONSTRAINT [FK_DDMDashboard_DDMUser]
GO
This is nothing to do with SCOPE_IDENTITY(), during your second insert:
INSERT INTO [dbo].[DDM_Dashboard] ([Dashboard_Name], [DDM_USER_ID])
VALUES (#p_dashboardName, SCOPE_IDENTITY())
You are only inserting into two columns [Dashboard_Name], and [DDM_USER_ID]. You do not specify a value for the column [Filter], which from your error message does not allow null values, therefore your insert fails.
DECLARE #Value1 varchar(50) = 'Test1', #Value2 varchar(50) = 'Test2';
DECLARE #Table1 table (Id int NOT NULL IDENTITY(1,1), Value varchar(50) NOT NULL);
DECLARE #Table2 table (Id int NOT NULL, Value varchar(50) NOT NULL);
INSERT INTO #Table1 (Value1)
OUTPUT inserted.Id, #Value2 INTO #Table2 (Id, Value)
Values (#Value1)
;
SELECT * FROM #Table1;
SELECT * FROM #Table1;
edit:
As GarethD pointed out, this is not actually a valid solution to your problem due to the foreign key constraint. However in other scenarios this is a useful way to handle cascading inserts and updates as it is an atomic operation of both records.
Related
My table definition:
CREATE TABLE [dbo].[Action](
[ActionId] [int] IDENTITY(1,1) NOT NULL,
[ActionType] [nvarchar](50) NOT NULL,
[Initiator] [nvarchar](256) NOT NULL,
[Date] [datetime] NOT NULL,
CONSTRAINT [PK_Action] PRIMARY KEY CLUSTERED
(
[ActionId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
Code I try to execute:
create trigger delete_on_titles on titles
after delete
as
begin
insert into Action (ActionType, Initiator, Date) values ('Add', USER_NAME(), getdate());
declare #id int = ##identity;
insert into Old_titles select * from deleted
update Old_titles set ActionId = #id where ActionId is null
end
But I get the error:
Msg 213, Level 16, State 1, Procedure delete_on_titles, Line 15 [Batch Start Line 2]
Column name or number of supplied values does not match table definition.
at the line "insert into Action (ActionType, Initiator, Date) values ('Add', USER_NAME(), getdate());"
What am I doing wrong?
UPDATED:
Thanks to #Larnu. Yes, the problem was in the line:
insert into Old_titles select * from deleted
I changed it to:
insert into Old_titles (
title_id, title, type, pub_id, price,
advance, royalty, ytd_sales, notes, pubdate)
select * from deleted
where title_id, title, type, pub_id, price, advance, royalty, ytd_sales, notes, pubdate are columns of the table deleted, and it works.
I have a system-versioning table with history table related as follows:
CREATE TABLE [dbo].[ExpenseCenter_Archive](
[ExpenseCenterId] [tinyint] NOT NULL,
[Name] [nvarchar](200) NOT NULL,
[LineCode] [smallint] NOT NULL,
[SysStartTime] [datetime2](2) NOT NULL,
[SysEndTime] [datetime2](2) NOT NULL
) ON [FG_HISTORY]
GO
-------
CREATE TABLE [dbo].[ExpenseCenter](
[ExpenseCenterId] [tinyint] NOT NULL,
[Name] [nvarchar](200) NOT NULL,
[LineCode] [smallint] NOT NULL,
[SysStartTime] [datetime2](2) GENERATED ALWAYS AS ROW START NOT NULL,
[SysEndTime] [datetime2](2) GENERATED ALWAYS AS ROW END NOT NULL,
CONSTRAINT [PK_ExpenseCenter] PRIMARY KEY CLUSTERED
(
[ExpenseCenterId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [FG_DATA],
CONSTRAINT [UK_ExpenseCenterName] UNIQUE NONCLUSTERED
(
[Name] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [FG_INDEX],
PERIOD FOR SYSTEM_TIME ([SysStartTime], [SysEndTime])
) ON [FG_DATA]
WITH
(
SYSTEM_VERSIONING = ON (HISTORY_TABLE = [dbo].[ExpenseCenter_Archive] , DATA_CONSISTENCY_CHECK = ON )
)
GO
Now, I want alter data type of 'LineCode' in system-version table and history. After changes once again enabling it as follows:
--- Before edit column
ALTER TABLE [dbo].[ExpenseCenter] SET (SYSTEM_VERSIONING = OFF);
-- ## Edit column in ssms ##
--- After edit column
ALTER TABLE [dbo].[ExpenseCenter]
SET
(
SYSTEM_VERSIONING = ON (HISTORY_TABLE = [dbo].[ExpenseCenter_Archive])
);
But I get the following error:
Cannot set SYSTEM_VERSIONING to ON when SYSTEM_TIME period is not defined.
How do I solve this issue.
From your question ,you are saying that ExpenseCenter_archive is the temporal table for ExpenseCenter..but error message says
you don't have system versioned table [dbo].[ExpenseCenter] ,if you want system versioned table ,Add system_time to it
so here are the steps,i would follow to make a table Temporal table of other..
if its for a new table ..
CREATE TABLE Department
(
DeptID int NOT NULL PRIMARY KEY CLUSTERED
, DeptName varchar(50) NOT NULL
, ManagerID INT NULL
, ParentDeptID int NULL
, SysStartTime datetime2 GENERATED ALWAYS AS ROW START NOT NULL
, SysEndTime datetime2 GENERATED ALWAYS AS ROW END NOT NULL
, PERIOD FOR SYSTEM_TIME (SysStartTime,SysEndTime)
)
WITH (SYSTEM_VERSIONING = ON)
;
if i need to alter data type for this newly created table..
MSDN recommends doing it in a transaction..
BEGIN TRAN
ALTER TABLE [dbo].[CompanyLocation] SET (SYSTEM_VERSIONING = OFF);
ALTER TABLE [CompanyLocation] ADD Cntr INT IDENTITY (1,1);
ALTER TABLE [dbo].[CompanyLocation]
SET
(
SYSTEM_VERSIONING = ON (HISTORY_TABLE = [dbo].[CompanyLocationHistory])
);
COMMIT ;
If i want to make an existing table Temporal,then i would do like below
ALTER TABLE dbo.Product
ADD StartTime DATETIME2 GENERATED ALWAYS AS ROW START
HIDDEN DEFAULT GETUTCDATE(),
EndTime DATETIME2 GENERATED ALWAYS AS ROW END
HIDDEN DEFAULT
CONVERT(DATETIME2, '9999-12-31 23:59:59.9999999'),
PERIOD FOR SYSTEM_TIME (StartTime, EndTime)
Now finally set Temporal ON
ALTER TABLE dbo.Product
SET (SYSTEM_VERSIONING = ON (HISTORY_TABLE=dbo.ProductHistory))
GO
References:
http://sqlhints.com/tag/modify-existing-table-as-system-versioned-temporal-table/
https://msdn.microsoft.com/en-us/library/mt590957.aspx
for alter system versioning table you don't need set SYSTEM_VERSIONING = OFF, but directly use ALTER TABLE ...
Let me explain this scenario, with my table structure-
RoomId RoomMemberId
R1 RM1
R1 RM2
R1 RM3
R2 Rm1
R2 RM2
R3 RM1
R3 RM4
R3 RM3
Here in the above table RM1,RM2 and RM3 are the member of R1 room ,
now I have to apply a constraint that there should not be any other room where only these three are members
i.e. there should not be any other room with same room members.
How can i do it at database end, by any unique constraint or any other way to do so ??
Pls help...
Example of Constraint is as given below :
Sample Table
CREATE TABLE TBLROOMTEST
(
ROOMID VARCHAR(100),
ROOMMEMBERID VARCHAR(100)
)
Create function
CREATE FUNCTION dbo.fn_RoomMemberCheck (#room_id varchar(100), #room_member varchar(100))
RETURNS int
AS
BEGIN
DECLARE #retval int
SELECT #retval = CASE WHEN ROOMID = #room_id THEN 1 ELSE 0 END
FROM TBLROOMTEST WHERE ROOMMEMBERID = #room_member
RETURN #retval
END;
Add constraint after table creation(but this can be done at the time of table creation itself):
ALTER TABLE TBLROOMTEST
ADD CONSTRAINT chk_IfMemberExistsInRoom CHECK (dbo.fn_RoomMemberCheck(ROOMID,ROOMMEMBERID)=0);
Note : It will give you error if you already have data in your table, thats why i asked the same to you. Reference is taken from
Here
If the number of room members are limited (say max 5), you could design the table horizontally instead of vertically and artifically make it vertically again in a view.
Room_ID Room_Label
----------- --------------------------------------------------
3 Aconcagua
1 Kilimanjaro
2 Mount Everest
Member_ID Member_GivenName Member_LastName
----------- -------------------------------------------------- --------------------------------------------------
1 Alice Smith
2 Bob Taylor
3 Cynthia Miller
4 Dan Cooper
RoomMember_ID Room_ID Member1_ID Member2_ID Member3_ID Member4_ID Member5_ID
------------- ----------- ----------- ----------- ----------- ----------- -----------
1 1 1 2 3 NULL NULL
2 2 1 2 NULL NULL NULL
3 3 1 2 3 4 NULL
And the view could look like this:
Room_ID Member_ID
----------- -----------
1 1
1 2
1 3
2 1
2 2
3 1
3 2
3 3
3 4
Then the RoomMember table needs a unique constraint over the members
ALTER TABLE StackOverflow.RoomMember
ADD CONSTRAINT UK_RoomMember01
UNIQUE NONCLUSTERED (
Member1_ID ASC, Member2_ID ASC, Member3_ID ASC, Member4_ID ASC, Member5_ID ASC
)
and a check constraint that ensures the members can only be entered in ascending order from the left to the right with NULL values to the right:
ALTER TABLE [StackOverflow].[RoomMember] WITH CHECK
ADD CONSTRAINT [CK_RoomMembers]
CHECK ((([Member2_ID] IS NULL OR [Member2_ID]>[Member1_ID]) AND ([Member3_ID] IS NULL OR [Member2_ID] IS NOT NULL AND [Member3_ID]>[Member2_ID]) AND ([Member4_ID] IS NULL OR [Member3_ID] IS NOT NULL AND [Member4_ID]>[Member3_ID]) AND ([Member5_ID] IS NULL OR [Member4_ID] IS NOT NULL AND [Member5_ID]>[Member4_ID])))
And that is it. It's now not possible to enter the same combination of members of another room, and the view provides still access in better normalized fashion.
Full source code here:
CREATE TABLE [StackOverflow].[Member](
[Member_ID] [int] IDENTITY(1,1) NOT NULL,
[Member_GivenName] [nvarchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[Member_LastName] [nvarchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
CONSTRAINT [PK_Member] PRIMARY KEY CLUSTERED
(
[Member_ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE TABLE [StackOverflow].[Room](
[Room_ID] [int] IDENTITY(1,1) NOT NULL,
[Room_Label] [nvarchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
CONSTRAINT [PK_Room] PRIMARY KEY CLUSTERED
(
[Room_ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
CONSTRAINT [UK_Room] UNIQUE NONCLUSTERED
(
[Room_Label] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE TABLE [StackOverflow].[RoomMember](
[RoomMember_ID] [int] IDENTITY(1,1) NOT NULL,
[Room_ID] [int] NOT NULL,
[Member1_ID] [int] NOT NULL,
[Member2_ID] [int] NULL,
[Member3_ID] [int] NULL,
[Member4_ID] [int] NULL,
[Member5_ID] [int] NULL,
CONSTRAINT [PK_RoomMember] PRIMARY KEY CLUSTERED
(
[RoomMember_ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
CONSTRAINT [UK_RoomMember01] UNIQUE NONCLUSTERED
(
[Member1_ID] ASC,
[Member2_ID] ASC,
[Member3_ID] ASC,
[Member4_ID] ASC,
[Member5_ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [StackOverflow].[Member] ADD CONSTRAINT [DF_Member_Member_GivenName] DEFAULT (N'') FOR [Member_GivenName]
GO
ALTER TABLE [StackOverflow].[RoomMember] WITH CHECK ADD CONSTRAINT [FK_RoomMember_Member1] FOREIGN KEY([Member1_ID])
REFERENCES [StackOverflow].[Member] ([Member_ID])
GO
ALTER TABLE [StackOverflow].[RoomMember] CHECK CONSTRAINT [FK_RoomMember_Member1]
GO
ALTER TABLE [StackOverflow].[RoomMember] WITH CHECK ADD CONSTRAINT [FK_RoomMember_Member2] FOREIGN KEY([Member2_ID])
REFERENCES [StackOverflow].[Member] ([Member_ID])
GO
ALTER TABLE [StackOverflow].[RoomMember] CHECK CONSTRAINT [FK_RoomMember_Member2]
GO
ALTER TABLE [StackOverflow].[RoomMember] WITH CHECK ADD CONSTRAINT [FK_RoomMember_Member3] FOREIGN KEY([Member3_ID])
REFERENCES [StackOverflow].[Member] ([Member_ID])
GO
ALTER TABLE [StackOverflow].[RoomMember] CHECK CONSTRAINT [FK_RoomMember_Member3]
GO
ALTER TABLE [StackOverflow].[RoomMember] WITH CHECK ADD CONSTRAINT [FK_RoomMember_Member4] FOREIGN KEY([Member4_ID])
REFERENCES [StackOverflow].[Member] ([Member_ID])
GO
ALTER TABLE [StackOverflow].[RoomMember] CHECK CONSTRAINT [FK_RoomMember_Member4]
GO
ALTER TABLE [StackOverflow].[RoomMember] WITH CHECK ADD CONSTRAINT [FK_RoomMember_Member5] FOREIGN KEY([Member5_ID])
REFERENCES [StackOverflow].[Member] ([Member_ID])
GO
ALTER TABLE [StackOverflow].[RoomMember] CHECK CONSTRAINT [FK_RoomMember_Member5]
GO
ALTER TABLE [StackOverflow].[RoomMember] WITH CHECK ADD CONSTRAINT [FK_RoomMember_Room] FOREIGN KEY([Room_ID])
REFERENCES [StackOverflow].[Room] ([Room_ID])
GO
ALTER TABLE [StackOverflow].[RoomMember] CHECK CONSTRAINT [FK_RoomMember_Room]
GO
ALTER TABLE [StackOverflow].[RoomMember] WITH CHECK ADD CONSTRAINT [CK_RoomMembers] CHECK ((([Member2_ID] IS NULL OR [Member2_ID]>[Member1_ID]) AND ([Member3_ID] IS NULL OR [Member2_ID] IS NOT NULL AND [Member3_ID]>[Member2_ID]) AND ([Member4_ID] IS NULL OR [Member3_ID] IS NOT NULL AND [Member4_ID]>[Member3_ID]) AND ([Member5_ID] IS NULL OR [Member4_ID] IS NOT NULL AND [Member5_ID]>[Member4_ID])))
GO
ALTER TABLE [StackOverflow].[RoomMember] CHECK CONSTRAINT [CK_RoomMembers]
GO
CREATE VIEW [StackOverflow].[V_RoomMember]
AS
SELECT Room_ID, Member1_ID AS Member_ID FROM StackOverflow.RoomMember
UNION
SELECT Room_ID, Member2_ID AS Member_ID FROM StackOverflow.RoomMember WHERE Member2_ID IS NOT NULL
UNION
SELECT Room_ID, Member3_ID AS Member_ID FROM StackOverflow.RoomMember WHERE Member3_ID IS NOT NULL
UNION
SELECT Room_ID, Member4_ID AS Member_ID FROM StackOverflow.RoomMember WHERE Member4_ID IS NOT NULL
UNION
SELECT Room_ID, Member5_ID AS Member_ID FROM StackOverflow.RoomMember WHERE Member5_ID IS NOT NULL
GO
SET IDENTITY_INSERT [StackOverflow].[Room] ON
GO
INSERT [StackOverflow].[Room] ([Room_ID], [Room_Label]) VALUES (3, N'Aconcagua')
GO
INSERT [StackOverflow].[Room] ([Room_ID], [Room_Label]) VALUES (1, N'Kilimanjaro')
GO
INSERT [StackOverflow].[Room] ([Room_ID], [Room_Label]) VALUES (2, N'Mount Everest')
GO
SET IDENTITY_INSERT [StackOverflow].[Room] OFF
GO
SET IDENTITY_INSERT [StackOverflow].[Member] ON
GO
INSERT [StackOverflow].[Member] ([Member_ID], [Member_GivenName], [Member_LastName]) VALUES (1, N'Alice', N'Smith')
GO
INSERT [StackOverflow].[Member] ([Member_ID], [Member_GivenName], [Member_LastName]) VALUES (2, N'Bob', N'Taylor')
GO
INSERT [StackOverflow].[Member] ([Member_ID], [Member_GivenName], [Member_LastName]) VALUES (3, N'Cynthia', N'Miller')
GO
INSERT [StackOverflow].[Member] ([Member_ID], [Member_GivenName], [Member_LastName]) VALUES (4, N'Dan', N'Cooper')
GO
SET IDENTITY_INSERT [StackOverflow].[Member] OFF
GO
SET IDENTITY_INSERT [StackOverflow].[RoomMember] ON
GO
INSERT [StackOverflow].[RoomMember] ([RoomMember_ID], [Room_ID], [Member1_ID], [Member2_ID], [Member3_ID], [Member4_ID], [Member5_ID]) VALUES (1, 1, 1, 2, 3, NULL, NULL)
GO
INSERT [StackOverflow].[RoomMember] ([RoomMember_ID], [Room_ID], [Member1_ID], [Member2_ID], [Member3_ID], [Member4_ID], [Member5_ID]) VALUES (2, 2, 1, 2, NULL, NULL, NULL)
GO
INSERT [StackOverflow].[RoomMember] ([RoomMember_ID], [Room_ID], [Member1_ID], [Member2_ID], [Member3_ID], [Member4_ID], [Member5_ID]) VALUES (3, 3, 1, 2, 3, 4, NULL)
GO
SET IDENTITY_INSERT [StackOverflow].[RoomMember] OFF
GO
I have create a table and a column of one of this table can accept null values. this table can be found below
CREATE TABLE [dbo].[tbl_Locations](
[location_ID] [int] IDENTITY(1,1) NOT NULL,
[location_Code] [varchar](100) NULL,
[location_Name] [varchar](250) NOT NULL,
CONSTRAINT [PK_tbl_Locations] PRIMARY KEY CLUSTERED
(
[location_ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
I created a trigger for this table so that when i insert, update or delete a record from this table, i will be able to audit the old record and new record. the below is the code that i am using:
IF EXISTS(SELECT * FROM inserted)
BEGIN
IF EXISTS(SELECT * FROM deleted)
BEGIN
...
END
ELSE
BEGIN
SET #NewValues = (SELECT * FROM inserted FOR XML AUTO);
SET #XXXID = (SELECT location_ID FROM inserted);
SET #Type = 'INSERT'; -- Row has been inserted
END
END
ELSE
...
The problem is that when i insert or update a record and the value of the column Code is null, the inserted table will only contain the values of the other two column. in other words, the null value is ignored:
<inserted location_ID="1" location_Name="Malta"/>
Is there a way how i can get the null value as well i.e. i get the below XML:
<inserted location_ID="1" location_Name="Malta"/>
Thanks in advance
In SQL Server 2008 R2, I have a simple table with the following columns definitions:
Id (PK ,int , not null)
MeterId (FK , int ,not null)
InstallDate(DateTime, not null)
Image(NVarCharMax, null)
Number (int , not null)
Comments(NVarChar(300), null)
And Id column is set as Identity .
When I run:
insert into Transmitters (MeterId, Number, InstallDate)
values (952, 777 , '2013-02-21')
I get the duplicate key error.
There is no other transmitter with id 777 ,
There is a meter with id 952.
This started happening in more than 1 table of my DB.
Any suggestions would be most appriceated.
The entire table script is:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Transmitters](
[Id] [int] IDENTITY(1,1) NOT NULL,
[MeterId] [int] NOT NULL,
[InstallDate] [datetime] NOT NULL,
[Image] [nvarchar](max) NULL,
[Number] [int] NOT NULL,
[Comments] [nvarchar](300) NULL,
CONSTRAINT [PK_Transmitters] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[Transmitters] WITH CHECK ADD CONSTRAINT [FK_Transmitter_Meter] FOREIGN KEY([MeterId])
REFERENCES [dbo].[Meter] ([Id])
GO
ALTER TABLE [dbo].[Transmitters] CHECK CONSTRAINT [FK_Transmitter_Meter]
GO
Ok , thanks guys you've been most helpful.
I've checked my identity current value using:
USE Name_Of_The_DB
GO
DBCC CHECKIDENT (‘Name_Of_The_Table’)
GO
It was indeed the cause of the problem that some rows had higher Id values than
the current identity.
Thand I inserted a row to update the current identity value:
set identity_insert YourTable ON
--Insert my row
set identity_insert YourTable OFF
Thanks :)