Click here to Skip to main content
15,921,351 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, I am using Stored procedure to enter data in the table. Following is my code Of table definition and stored procedure.
SQL
CREATE TABLE [StarBazar].[ProductSale] (
    [ProductSaleId] INT           IDENTITY (1, 1) NOT NULL,
    [ProductId]     INT           NOT NULL,
    [C_Id]          INT           NOT NULL,
    [Quantity]      INT           NOT NULL,
    [DateOfSale]    DATETIME2 (7) NOT NULL,
    PRIMARY KEY CLUSTERED ([ProductSaleId] ASC),
    FOREIGN KEY ([ProductId]) REFERENCES [StarBazar].[Products] ([Id]),
    FOREIGN KEY ([C_Id]) REFERENCES [StarBazar].[ClientDetails] ([ClientId])
);


CREATE PROCEDURE [dbo].[usp_InsertProductSale]
	@schemaname nvarchar(20),
	@productid int,
	@clientid int,
	@quantity int
AS
   declare @sql as nvarchar(max)
   set @sql=N'insert into [' +@schemaname + N'].[ProductSale](ProductId,C_Id,Quantity,DateOfSale)
            values(' +CONVERT(NVARCHAR,@productid) + N','+CONVERT(NVARCHAR,@clientid) + N','
			+ CONVERT(NVARCHAR,@quantity)+ N','''+CONVERT(nvarchar,SYSDATETIME()) +N''')'
			print (@sql)
			exec (@sql)
RETURN 0

When I execute the procedure, it gives the following error.
insert into [StarBazar].[ProductSale](ProductId,C_Id,Quantity,DateOfSale)
values(1,1,1,'2015-06-25 10:30:35.0210666')

(1 row(s) affected)

Msg 547, Level 16, State 0, Line 3
The INSERT statement conflicted with the FOREIGN KEY constraint "FK__ProductSa__Clien__56B3DD81". The conflict occurred in database "ReportSystem", table "StarBazar.ClientDetails", column 'ClientId'.
The statement has been terminated.

Help me to solve this.
Posted
Comments
PIEBALDconsult 25-Jun-15 1:13am    
Add the appropriate record to StarBazar.

You are inserting forienkey reference value of a usp_InsertProductSale table first,so it gives an exception.
Must confirm ProductId and C_Id is exists in usp_InsertProductSale table.
if not exists then you have to first insert it in usp_InsertProductSale then only you can insert it
in ProductSale table.
 
Share this answer
 
A foreign key is a reference to a unique value in a different table, and SQL will ensure "referential integrity" - which means it won't let you end you with "orphaned" key references. When you insert a value to a foreign key column it must be a null or a existing reference to a row in the other table, and when you delete, you must delete the row containing the foreign key first, then the row it references.

If you don't, you will get an error such as you describe.

So enter the row into the "main" table first, then enter the "dependant" table information second.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900