Microsoft SQL Server - check constraint error when using stored procedure (msg 547) - sql

I keep getting the following error:
Msg 547, Level 16, State 0, Procedure add_new_customer, Line 6
The INSERT statement conflicted with the CHECK constraint "CK__customer__addres__09A971A2". The conflict occurred in database "AIT 732 - Bank", table "dbo.customer", column 'address_state'.
The following is table that I am attempting to update:
create table customer
(
cust_id numeric(10,0) not null identity primary key,
social_security_num numeric(9,0) not null,
first_name varchar(20) not null,
last_name varchar(20) not null,
primary_address varchar(50) not null,
address_zip_code numeric(5,0) not null,
address_state char(2) check (address_state in('md','pa','dc', 'de', 'wv', 'va','nj')),
gender char(1) not null check (gender in('m','f')),
phone_num numeric(10,0) null
)
this is the stored procedure i created:
create procedure add_new_customer
(#social_sec numeric, #f_name varchar, #l_name varchar, #pri_address varchar, #zip numeric, #add_state char, #gender char, #phone numeric)
as
begin
begin transaction
insert into customer(
social_security_num,
first_name,
last_name,
primary_address,
address_zip_code,
address_state,
gender,
phone_num)
values (
#social_sec,
lower(#f_name),
lower(#l_name),
lower(#pri_address),
#zip,
lower(#add_state),
lower(#gender),
#phone)
if ##ERROR != 0
begin
rollback transaction
return ##error
end
commit transaction
end
and last but not least, this is how I am calling procedure
add_new_customer 211118888, 'Bob', 'JONES', '222 some st', 21333, 'md', 'm', 4102227878
I've been messing with this for about and hour and can not figure out where that error is coming from. any help would be appreciated.

Your stored proc parameter definition is #add_state char but this will truncate your input value of 'md' to 'm' which isn't a valid value. Change you parameter definition to match the table defn char(2) and it should then work.

Related

Unable to create trigger in PhpMyAdmin

Happy Thanksgiving!
I am trying to create a trigger phpmyadmin to update a salary amount.
I made the following table:
CREATE TABLE `salaryraise` (
`SalaryChangeID` decimal(12,0) NOT NULL,
`OldRate` decimal(8,2) NOT NULL,
`NewRate` decimal(8,2) NOT NULL,
`TeacherID` decimal(12,0) NOT NULL,
`ChangeDate` date NOT NULL
)
And I have my existing teacher_data Table
CREATE TABLE `teacherdata` (
`teacher_data_id` int(12) NOT NULL,
`gender` varchar(12) NOT NULL,
`race` varchar(12) NOT NULL,
`hire_date` date NOT NULL,
`salary` decimal(8,2) NOT NULL,
`certicationValid` varchar(12) NOT NULL,
`subjectTaught` varchar(32) NOT NULL
)
And I am trying to run my trigger
CREATE TRIGGER SalaryRaise
On Teacher
AFTER UPDATE
AS
BEGIN
DECLARE #OldRate DECIMAL(8,2) = (SELECT Rate FROM DELETED);
DECLARE #NewRate DECIMAL(8,2) = (SELECT Rate FROM INSERTED);
IF (#OldRate <> #NewRate)
INSERT INTO salaryraise(SalaryRaiseID, OldRate, NewRate, teacher_id, ChangeDate)
VALUES (ISNULL((SELECT MAX(SalaryRaiseID)+1 FROM SalaryRaise),1),
#OldRate,
#NewRate,
(SELECT teacher_id FROM INSERTED),
GETDATE());
END;
I get the following error in PHPMYADMIN
CREATE TRIGGER SalaryRaise
On Teacher
AFTER UPDATE
AS
BEGIN
DECLARE #OldRate DECIMAL(8,2) = (SELECT Rate FROM DELETED);
MySQL said: Documentation
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'On Teacher
AFTER UPDATE
AS
BEGIN
DECLARE #OldRate DECIMAL(8,2) = (SELECT...' at line 2
Please Advise

Check column data type and change it in SQL Server

All I want to do is check if the hire_state column's data type is bit, and if so, change it to SmallInt.
Here is my code
IF OBJECT_ID(N'dbo.employees') IS NULL
BEGIN
CREATE TABLE dbo.employees
(
employees_id INT IDENTITY(1, 1) PRIMARY KEY,
employees_number INT NOT NULL,
first_name NVARCHAR(120) NOT NULL,
last_name NVARCHAR(120) NOT NULL,
birthday DATE NOT NULL,
gender TINYINT NOT NULL,
hire_date DATE NOT NULL,
phone1 NCHAR(25) NOT NULL,
phone2 NVARCHAR(25),
home_address NVARCHAR(255) NOT NULL,
granty NVARCHAR(250),
hire_state BIT NOT NULL DEFAULT 1,
leave_Date DATE,
job SMALLINT NOT NULL
);
END
ELSE
BEGIN
IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS C
WHERE C.TABLE_NAME = N'employees'
AND C.COLUMN_NAME = 'employee_image')
ALTER TABLE dbo.employees
ADD employee_image NVARCHAR(255)
ALTER TABLE dbo.employees
ALTER COLUMN hire_state TINYINT NOT NULL
END;
How can I check whether hire_state is bit or not and then change it to TinyInt?
When I execute my code shown above, I get this error
Msg 5074, Level 16, State 1, Line 49
The object 'DF__employees__hire___267ABA7A' is dependent on column 'hire_state'.
Msg 4922, Level 16, State 9, Line 49
ALTER TABLE ALTER COLUMN hire_state failed because one or more objects access this column.
I did not use hire_state in any other table
Ok I Change my code base on comment and it work
IF EXISTS (SELECT * FROM sys.columns WHERE name =
N'hire_state' AND
object_id= OBJECT_ID('dbo.employees') AND
system_type_id = 104)
BEGIN
ALTER TABLE dbo.employees DROP CONSTRAINT DF__employees__hire___267ABA7A
ALTER TABLE dbo.employees ALTER COLUMN hire_state TINYINT NOT NULL
END;

SQL Trigger throws error but still inserts

I am working on a trigger that is supposed to block an insert when #verkoperstatus is 0; this does function, but for some reason it also stops the insert when #verkoperstatus is 1. What could be the root cause behind this?
CREATE TRIGGER [dbo].[verkoper_check] ON [dbo].[Verkoper]
FOR INSERT,UPDATE
AS
BEGIN
DECLARE #verkoperstatus bit
DECLARE #gebruikersnaam varchar(25)
SELECT #gebruikersnaam = gebruikersnaam FROM inserted
SELECT #verkoperstatus = verkoper FROM Gebruiker WHERE gebruikersnaam = #gebruikersnaam
IF #verkoperstatus = 0
BEGIN
RAISERROR('Geen verkoper!',18,1);
ROLLBACK;
END
ELSE
BEGIN
COMMIT;
END
END
It should insert when #verkoperstatus is 1, and raise an error when #verkopstatus is 0.
The table Gebruiker is references, which includes a 'gebruikersnaam' and a 'verkoper' column. The value of the 'gebruikersnaam' column is the identifying column which (in this specific case is 'Lars'). Verkoper is a bit column, which indicated if one is a seller or not, so this has the value of a 0 or a 1.
The goal I am trying to achieve is to have an insert on the Verkoper tabel if a 'gebruikersnaam' has the 'verkoper' value of one.
This means if there is a row in Gebruiker with the 'gebruikersnaam' of Lars and the verkoper has a value of 1. This will be an allowed insert into the Verkoper tabel.
As the Verkoper has the following columns: 'gebruikersnaam', 'banknaam', 'rekeningnummer', 'controleoptienaam' and 'creditcardnummer'. When 'gebruikersnaam' corresponds with a 'gebruikersnaam' from the Gebruikers table AND has a value of 1 in the 'verkoper' column this record will be allowed to be inserted into the Verkoper table.
As of now there is a row in the Gebruikers column which includes the gebruikersnaam 'Lars' and a verkoper value of '1'. Meaning any SQL Insert with the gebruikersnaam of 'Lars' should be allowed into the Verkoper table.
This however does not function the way I believe it should.
These are the tables mentioned above:
CREATE TABLE Verkoper (
gebruikersnaam varchar(25) NOT NULL,
banknaam varchar(255) NULL,
rekeningnummer varchar(32) NULL,
controleoptienaam char(10) NOT NULL,
creditcardnummer integer NULL,
CONSTRAINT pk_Verkoper PRIMARY KEY (gebruikersnaam),
CONSTRAINT fk_Verkoper_Gebruikersnaam FOREIGN KEY (gebruikersnaam) REFERENCES Gebruiker(gebruikersnaam),
CONSTRAINT ck_rekening CHECK (rekeningnummer is NOT NULL OR creditcardnummer is NOT NULL),
CONSTRAINT ck_controleoptie CHECK (controleoptienaam IN('Post', 'Creditcard'))
)
CREATE TABLE Gebruiker(
gebruikersnaam varchar(25) NOT NULL,
voornaam varchar(25) NOT NULL,
achternaam varchar(25) NOT NULL,
adresregel_1 varchar(255) NULL,
adresregel_2 varchar(255) NULL,
postcode char(7) NULL,
plaatsnaam varchar(255) NULL,
land varchar(255) NULL,
geboortedag char(10) NOT NULL,
mailbox varchar(255) NOT NULL,
wachtwoord varchar(255) NOT NULL,
verkoper bit NOT NULL,
CONSTRAINT pk_gebruiker PRIMARY KEY (gebruikersnaam),
)
For the inserts I am using the following data:
INSERT INTO Gebruiker VALUES ('Lars', 'Lars', 'Last_name', null, null, null, null, null, '04/04/2019', 'lars#mymailbox.cloud', 'MyPassword', 1)
INSERT INTO Verkoper VALUES ('Lars', 'ING', 'NL32ABN32492809', 'Post', null)
This is untested, however, I suspect this is the logic you really need:
CREATE TRIGGER [dbo].[verkoper_check] ON [dbo].[Verkoper]
FOR INSERT,UPDATE
AS BEGIN
IF EXISTS(SELECT 1
FROM inserted i
JOIN Gebruiker G ON i.gebruikersnaam = G.gebruikersnaam
WHERE G.verkoper = 0) BEGIN
RAISERROR('Geen verkoper!',18,1);
ROLLBACK;
END;
END;

Arithmetic overflow error converting expression to data type int, How do I resolve this?

This is the code that created the table.
CREATE TABLE CUSTOMERS
(
Customer_ID INT NOT NULL,
CHECK(Customer_ID <= 11),
First_Name varchar(20) NOT NULL,
Last_Name varchar(30),
Home_Street varchar(30),
Home_City varchar(20),
Home_State varchar(2),
Home_Zip varchar(5),
PhoneNumber varchar(11) NOT NULL
);
ALTER TABLE CUSTOMERS
ADD CONSTRAINT PK_CUSTOMERS PRIMARY KEY(Customer_ID);
Then I try to insert data (using this code) into the table and that is where I get this error.
INSERT INTO dbo.CUSTOMERS(Customer_ID, First_Name, Last_Name, Home_Street, Home_City, Home_State, Home_Zip, PhoneNumber)
VALUES (11223344556, 'John', 'Doe', '1234 Hand Street', 'Wahiawa', 'HI', 96786, 2535551267);
What am I doing wrong and what can I do to fix this issue?
AS per my understanding you are checking length of Customer_ID <=11 so you should mention len(Customer_ID)<=11 it will work and you should alter datatype of Customer_ID int to bigint
CREATE TABLE CUSTOMERS
(
Customer_ID bigINT NOT NULL,
CHECK(len(Customer_ID)<=11),
First_Name varchar(20) NOT NULL,
Last_Name varchar(30),
Home_Street varchar(30),
Home_City varchar(20),
Home_State varchar(2),
Home_Zip varchar(5),
PhoneNumber varchar(11) NOT NULL
);
ALTER TABLE CUSTOMERS
ADD CONSTRAINT PK_CUSTOMERS
PRIMARY KEY(Customer_ID);
INSERT INTO dbo.CUSTOMERS(Customer_ID,First_Name,Last_Name,Home_Street,
Home_City,Home_State,Home_Zip,PhoneNumber)
VALUES(11223344556,'John','Doe','1234 Hand Street',
'Wahiawa','HI',96786,2535551267);
You need customer id to be bigint:
CREATE TABLE CUSTOMERS
(
Customer_ID BIGINT NOT NULL,
CHECK(Customer_ID<=11),
First_Name varchar(20) NOT NULL,
Last_Name varchar(30),
Home_Street varchar(30),
Home_City varchar(20),
Home_State varchar(2),
Home_Zip varchar(5),
PhoneNumber varchar(11) NOT NULL
);
ALTER TABLE CUSTOMERS
ADD CONSTRAINT PK_CUSTOMERS
PRIMARY KEY(Customer_ID);
The problem may be due to CHECK(Customer_ID<=11) since Customer_ID id integer datatype the server may check for integer validation and not length validation. Try to change the validation.

Error converting data type varchar to int.?

My table is below
CREATE TABLE Customers
(
CustomerID int identity(1,1) not null primary key,
Name varchar(50) not null,
PhoneNumber varchar(20) not null
constraint chk_PhoneNumber check(PhoneNumber not like '%[^0-9]%'),
DoorNo varchar(50) not null,
StreetName varchar(50) not null,
City varchar(50) not null,
Statee varchar(50) not null,
Zipcode int not null
)
My stored procedure:
ALTER PROCEDURE stp_customers_insert
(#customerid int,
#name varchar(50),
#phone varchar(50),
#doorno varchar(50),
#streetname varchar(50),
#city varchar(50),
#state varchar(50),
#zip int)
AS
BEGIN
IF EXISTS (SELECT CustomerID FROM Customers WHERE CustomerID = #customerid)
BEGIN
RAISERROR ('employee id already exists', 1, 1)
END
ELSE
BEGIN
INSERT INTO Customers (Name, PhoneNumber, DoorNo, StreetName, City, Statee, Zipcode)
VALUES (#name, #phone, #doorno, #streetname, #city, #state, #zip)
END
END
Sample call:
exec stp_customers_insert 'ram', '674673932', '122', '5th cross', 'trichy', 'tamilnadu', 620001
I get this error:
Msg 8114, Level 16, State 5, Procedure stp_customers_insert, Line 23
Error converting data type varchar to int.
The problem appears to be that your stored procedure expects 8 parameters:
stp_customers_insert(#customerid int, #name varchar(50), #phone varchar(50),
#doorno varchar(50), #streetname varchar(50), #city varchar(50),
#state varchar(50), #zip int)
but you are only passing 7 parameters when you actually call the proc:
exec stp_customers_insert 'ram','674673932','122','5th cross','trichy','tamilnadu',620001
If you don't know or don't want to perform the duplicate check on the CustomerID, then you could slightly modify your call to just pass NULL:
exec stp_customers_insert NULL, 'ram','674673932','122','5th cross','trichy','tamilnadu',620001
As an aside, if the proc is not even inserting the CustomerID, and this field is auto increment, then I don't see the point of passing it. Instead, you might want to consider using a unique constraint to achieve the same.
exec stp_customers_insert 1,'ram','674673932','122','5thcross','trichy','tamilnadu',620001
You have to pass #customerid value in procedure parameters - then it will execute without error.
In your table structure CustomerID is defined as INT. But as your stored procedure is defined in this format:
stp_customers_insert(#customerid int,#name ....
You are sending ram as value for customerid in
exec stp_customers_insert 'ram','674673932'....
Correct this to:
exec stp_customers_insert '*enter the CustId value here*','ram','674673932'....
Replace *enter the CustId value here* with the CustomerID
Also change:
insert into Customers(Name,PhoneNumber,DoorNo,StreetName,City,Statee,Zipcode) values(#name,#phone,#doorno,#streetname,#city,#state,#zip)
To include CustomerID as:
insert into Customers(CustomerID,Name,PhoneNumber,DoorNo,StreetName,City,Statee,Zipcode) values(#customerid,#name,#phone,#doorno,#streetname,#city,#state,#zip)
I suggest remove #customerid from sp CustomerID is auto increment field so no need to pass any value for CustomerID. It should be like this:
alter procedure stp_customers_insert(#name varchar(50),#phone varchar(50),#doorno varchar(50),#streetname varchar(50),#city varchar(50),#state varchar(50),#zip int)
as
begin
if exists(select CustomerID from Customers where Name = #name ,phone = #phone ,doorno = #doorno ,streetname = #streetname ,city= #city,state= #state , zip = #zip )
begin
raiserror('employee id already exists',1,1)
end
else
begin
insert into Customers(Name,PhoneNumber,DoorNo,StreetName,City,Statee,Zipcode) values(#name,#phone,#doorno,#streetname,#city,#state,#zip)
end
end
exec stp_customers_insert 'ram','674673932','122','5th cross','trichy','tamilnadu',620001