My INSERT statement conflicted with the FOREIGN KEY constraint - sql

enter image description here
Those are my diagrams - I create procedure
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[hasta]
#Ad nchar(50),
#Soyadı nvarchar(100),
#TcKimlik nchar(11),
#DogumTarihi varchar(8),
#TelefonNo nvarchar(11)
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO [dbo].Hastalar ([Ad], [Soyadı], [TcKimlik], [DogumTarihi], [TelefonNo])
VALUES (#Ad, #Soyadı, #TcKimlik, #DogumTarihi, #TelefonNo)
END
After I want add data in Hastalar table, I write
exec hasta 'Emir','Yılmaz','35635993564','1995.11.19','05347331085'
but I get this error
Msg 547, Level 16, State 0, Procedure hasta, Line 13
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Hastalar_Testler". The conflict occurred in database "hastane", table "dbo.Testler", column 'TestID'. The statement has been terminated.

In your table [dbo].Hastalar, it has a foreign key reference to another table. The way a FK works is it cannot have a value in that column that is not also in the primary key column of the referenced table.
If you have SQL Server Management Studio, open it up and sp_help '[dbo].Hastalar'. See which column that FK is on, and which column of which table it references. You're inserting some bad data.

What part of the error do you not understand?
The message is saying that one of the columns -- "TestId" -- is referring to another table. And the value being inserted is not already in that table.
You are not explicitly inserting a value for TestId, so that value is being set using a default constraint or trigger. I would suggest that you explicit provide the value in the insert -- even if that value is NULL.

Related

Error in changing column length in Postgres

I am trying to change the column size from 100 to 150 varchar data type using following query:
alter table data_warehouse.tbl_abc
alter column first_nm varchar(150) null;
Getting the following error:
SQL Error [42601]: ERROR: syntax error at or near "varchar"
Position: 77
The syntax is a bit different, so try this:
ALTER TABLE data_warehouse.tbl_abc
ALTER COLUMN first_nm type varchar(120);
The error in your syntax is that you missed a TYPE keyword:
ALTER TABLE data_warehouse.tbl_abc
ALTER COLUMN first_nm TYPE varchar(150);
and if you have a NOT NULL constraint you want to remove, add a new ALTER COLUMN inside the same ALTER TABLE statement:
ALTER TABLE data_warehouse.tbl_abc
ALTER COLUMN first_nm TYPE varchar(150),
ALTER COLUMN first_nm DROP NOT NULL;
for reference look here: https://www.postgresql.org/docs/current/sql-altertable.html
Edit: as in the comment, if you have a view which involves the same column, drop it and re-create it under transaction:
BEGIN TRANSACTION;
DROP VIEW [...];
ALTER TABLE [...];
CREATE VIEW [...];
COMMIT;
Be aware that to alter a table, you must acquire an exclusive lock on it, so during the whole process, all the queries over the same table and on the views of the table are locked, also if they don't read from the altered column (because the whole table is locked) - use with caution in production environment

How to automatically update second table with some same information after insert into first table

When I enter a new record in one table, I need to have some of the information from the first table be automatically added to the second table. I unsuccessfully tried triggers to do this.
My primary table looks like this:
CREATE TABLE demographics (
person_local_id BIGSERIAL UNIQUE PRIMARY KEY,
first_name VARCHAR(50)...[other lines]
);
I set up the child table like this:
CREATE TABLE pedigree (
pedigree_id BIGSERIAL PRIMARY KEY NOT NULL,
person_local_id BIGSERIAL NOT NULL,
person_sex VARCHAR(10),
father VARCHAR(10) DEFAULT 0,
mother VARCHAR(10) DEFAULT 0,
FOREIGN KEY (person_local_id) REFERENCES demographics (person_local_id)
ON DELETE CASCADE ON UPDATE CASCADE
);
My approach was to create a trigger on the demographics primary table such that any time a record was added to it, a corresponding record would be added to the pedigree table consisting of just the person_local_id. I added a foreign key on the pedigree table that referenced the column in the demographics that I need to copy over to the pedigree table in that column.
Then I created a trigger, but it doesn't work. I tried this with and without the word "EXECUTE".
CREATE TRIGGER into_pedigree AFTER INSERT OR UPDATE ON demographics
FOR EACH ROW EXECUTE INSERT INTO pedigree (person_local_id) SELECT (NEW.person_local_id) FROM NEW;
I keep getting syntax errors but I can't identify the error:
ERROR: syntax error at or near "INSERT"
LINE 2: FOR EACH ROW EXECUTE INSERT INTO pedigree (person_local_id) ...
^
I also tried this, adding the name:
CREATE TRIGGER into_pedigree ON identify_relatives_database.demographics
AFTER INSERT
AS
BEGIN
INSERT INTO pedigree (person_local_id) VALUES (INSERTED.person_local_id)
END;
But I get the error message:
ERROR: syntax error at or near "ON"
LINE 1: CREATE TRIGGER into_pedigree ON demographics
^
I appreciate your assistance.
You may try this.
CREATE TRIGGER [dbo].[Customer_INSERT]
ON [dbo].[demographics]
AFTER INSERT, UPDATE
AS
BEGIN
SET NOCOUNT ON;
DECLARE #CustomerId INT
SELECT #CustomerId = INSERTED.person_local_id FROM INSERTED
IF EXISTS ( SELECT * FROM PEDIGREE WHERE person_local_id = #CustomerId)
BEGIN
--- here col is the required column name need to be modified,
--- since you are inserting person_local_id from base table which is auto generated and not suppose to be change in any condition
UPDATE PEDIGREE SET COL = INSERTED.COL WHERE person_local_id = #CustomerId
END
ELSE
BEGIN
INSERT INTO pedigree (person_local_id)
VALUES(#CustomerId)
END
END
Although I don't find anything related to your update part. Since you are inserting primary key from base table as foreign key in child table, so for normalization it is not going to changed in any condition. So i don't think you need update part in your trigger Hence your required trigger will be:
CREATE TRIGGER [dbo].[Customer_INSERT]
ON [dbo].[demographics]
AFTER INSERT
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO pedigree (person_local_id)
SELECT INSERTED.person_local_id FROM INSERTED
END
You should try this :
CREATE TRIGGER into_pedigree ON demographics
FOR INSERT
AS
insert into pedigree (person_local_id)
values(inserted.person_local_id);
PRINT 'AFTER INSERT trigger fired.'
GO

SQL Error: The Insert statement conflicted with the CHECK constraint

Just learning the SQL language. Trying to insert data into a table but keep getting the following error:
"The INSERT statement conflicted with the CHECK constraint
"JOB_JOBCODE". The conflict occurred in database "qwerty", table
"dbo.Job", column 'jobCode'."
Code:
This is the table I'm creating, nothing fancy
CREATE TABLE Job(
jobCode char(4),
jobdesc varchar(50),
--ADD CONSTRAINT PK JPB CODE
CONSTRAINT PK_JobCode PRIMARY KEY(jobCode) ,
CONSTRAINT JOB_JOBCODE CHECK (jobCode in ('CAST’, ‘ENGI’, ‘INSP’, ‘PMGR')) );
This is the data that I'm inserting
INSERT INTO Job VALUES ('CAST', 'Cast Member);
Any help would be appreciated, Im not sure what I'm doing wrong
Use this query for inserting values into Job table
INSERT INTO Job VALUES ('CAST', 'Cast Member');
Run this to fix your check literal error:
ALTER TABLE Job DROP JOB_JOBCODE
ALTER TABLE Job ADD CONSTRAINT JOB_JOBCODE CHECK (jobCode IN ('CAST', 'ENGI', 'INSP', 'PMGR'))
Then use the explicit column form of the insert:
INSERT INTO Job (jobCode, jobdesc)
VALUES ('CAST', 'Cast Member')
Make sure to use the proper literal delimiter '.

Change length of column of table which have dependencies

I've got a table named Contacts with column Title varchar(50) . Now in the middle of development I want to change the length to varchar(100) of field Title .At the moment table Contacts has over 25 dependencies (other tables, views functions).
When I run following sql statement in sql server 2008 . I am getting errors.
ALTER TABLE [Contacts ] ALTER COLUMN [Title ] varchar(100)
Error Like
Msg 5074, Level 16, State 1, Line 2
The object 'Contacts_title' is dependent on column 'title'.
And more.
you have to drop are recreate the constrains on the Contact table to do that or (sometime not really recommended ) you can temporary disable the constrain, alter the length and enable them again
--disable all constraints for the Sales.SalesOrderHeader table
ALTER TABLE [yourtable] NOCHECK CONSTRAINT ALL
--do your stuff
--do something --enable all constraints for the Sales.SalesOrderHeader table
ALTER TABLE [yourtable] CHECK CONSTRAINT ALL
You have to remove the dependence, and then create it again.

set identity on the column

How can I modify table and set identity on PK column using T-SQL?
thanks for help
You can't modify an existing column to have the IDENTITY "property" - you have to:
create a new table with the same structure (but with IDENTITY set up),
turn on IDENTITY_INSERT for this new table,
insert rows from the old table into the new table,
drop the old table, and,
rename the new table to have the old table name.
If there are foreign keys involved, you need to fix those up also.
The problem with most solutions to this question is that they require either adding a new column to the table or completely rebuilding the table.
Both can require large amounts of locking and logging activity which I have always found annoying as this is a metadata only change and shouldn't necessitate touching the data pages at all (Indeed it is possible to update the metadata directly by starting the instance in single user mode and messing around with some columns in sys.syscolpars but this is undocumented/unsupported.)
However the workaround posted on this connect item shows a completely supported way of making this into a metadata only change using ALTER TABLE...SWITCH (credit SQLKiwi)
Example code.
Set up test table with no identity column.
CREATE TABLE dbo.tblFoo
(
bar INT PRIMARY KEY,
filler CHAR(8000),
filler2 CHAR(49)
)
INSERT INTO dbo.tblFoo (bar)
SELECT TOP (10000) ROW_NUMBER() OVER (ORDER BY (SELECT 0))
FROM master..spt_values v1, master..spt_values v2
Alter it to have an identity column (more or less instant).
BEGIN TRY;
BEGIN TRANSACTION;
/*Using DBCC CHECKIDENT('dbo.tblFoo') is slow so use dynamic SQL to
set the correct seed in the table definition instead*/
DECLARE #TableScript nvarchar(max)
SELECT #TableScript =
'
CREATE TABLE dbo.Destination(
bar INT IDENTITY(' +
CAST(ISNULL(MAX(bar),0)+1 AS VARCHAR) + ',1) PRIMARY KEY,
filler CHAR(8000),
filler2 CHAR(49)
)
ALTER TABLE dbo.tblFoo SWITCH TO dbo.Destination;
'
FROM dbo.tblFoo
WITH (TABLOCKX,HOLDLOCK)
EXEC(#TableScript)
DROP TABLE dbo.tblFoo;
EXECUTE sp_rename N'dbo.Destination', N'tblFoo', 'OBJECT';
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
IF XACT_STATE() <> 0 ROLLBACK TRANSACTION;
PRINT ERROR_MESSAGE();
END CATCH;
Test the result.
INSERT INTO dbo.tblFoo (filler,filler2)
OUTPUT inserted.*
VALUES ('foo','bar')
Gives
bar filler filler2
----------- --------- ---------
10001 foo bar
Clean up
DROP TABLE dbo.tblFoo
Is it the answer you are looking for?
DBCC CHECKIDENT(
'DBName.dbo.TableName'
,RESEED --[, new_reseed_value ]
)
Example use:
DBCC CHECKIDENT(
'DBName.dbo.TableName'
)
Checking identity information: current identity value '1', current column value '1211031236'.
DBCC execution completed. If DBCC printed error messages, contact your system administrator.
DBCC CHECKIDENT(
'DBName.dbo.TableName'
,RESEED --[, new_reseed_value ]
)
Checking identity information: current identity value '1211031236', current column value '1211031236'.
DBCC execution completed. If DBCC printed error messages, contact your system administrator.
In fact, you can modify the IDENTITY on a column.
Please read through this article http://www.sqlmag.com/article/tsql3/adding-the-identity-property-to-an-existing-column.aspx
It will need a lot more code than ALTER TABLE tab ALTER COLUMN col SET IDENTITY, though
You need to use the ALTER TABLE command - always test first in dev or pre-production!
The example G seems closest to your requirement:
CREATE TABLE dbo.doc_exe ( column_a INT CONSTRAINT column_a_un UNIQUE) ;
GO
ALTER TABLE dbo.doc_exe ADD
-- Add a PRIMARY KEY identity column.
column_b INT IDENTITY
CONSTRAINT column_b_pk PRIMARY KEY,
See http://msdn.microsoft.com/en-us/library/ms190273.aspx
Since you can only ignore identity columns for insert, not for update, you'll need an intermediate table. Here's an example:
create table TestTable (pk int constraint PK_TestTable primary key,
name varchar(30))
create table TestTable2 (pk int constraint PK_TestTable identity primary key,
name varchar(30))
set identity_insert TestTable2 on
insert TestTable2 (pk, name) select pk, name from TestTable
set identity_insert TestTable2 off
drop table TestTable
exec sp_rename 'TestTable2', 'TestTable'