I'm working on some example questions in Microsoft SQL Server Management Studio. I am very lost on this question, if anyone could explain how to go about transferring an attribute like that I would appreciate it. I'll attach the tables of a simple database that I'm testing with.
Create a stored procedure that accepts an AreaID and a handlerID. The procedure will transfer an area from one Handler to another.
When the area is transferred the new Handler will have $25.00 added their Salary and the old Handler will have $25.00 subtracted from their Salary.
Remember to update all tables as needed as well as include a transaction and error catching
Code:
Create Table Runner
(
RunnerID int identity (1,1) not null
Constraint PK_Runner primary key clustered,
RunnerFirstName varchar(30) not null,
RunnerLastName varchar(30) not null,
Phone char(10) not null
Constraint ck_Phone check (Phone like '[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]')
)
Create Table DevSite
(
DevSiteId int not null
Constraint PK_DevSite primary key clustered,
DevSiteName varchar(50) not null,
DevSiteAddress varchar(60) not null
)
Create Table Handler
(
handlerID int identity (1,1) not null
Constraint PK_Handler primary key clustered,
HandlerFirstName varchar(30) not null,
HandlerLastName varchar(30) not null,
PagerNumber char(10) not null
Constraint ck_pager check (PagerNumber like '[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]'),
Salary smallmoney not null Constraint CK_Salary check(Salary >= 0) Constraint df_Salary default 12.00
)
Create Table Area
(
AreaID int not null
Constraint PK_Area primary key clustered,
AreaName varchar(50) not null,
AreaSupeFirstName varchar(30) not null,
AreaSupeLastName varchar(30) not null,
handlerID int not null constraint fk_AreaToHandler references Handler(handlerID)
)
Create Table Direction
(
DirectionID int not null Constraint PK_Direction primary key clustered,
DirectionName varchar(50) not null,
EstimatedTime varchar(3) not null,
AreaID int not null Constraint FK_RouteToArea references Area (AreaID),
DevSiteID int not null Constraint FK_RouteToDevSite references DevSite (DevSiteID),
RunnerId int not null Constraint FK_RouteToRunner references Runner (RunnerId)
)
Create Table Consumer
(
ConsumerID int not null Constraint PK_Consumer primary key clustered,
ConsumerFirstName varchar(30) not null,
ConsumerLastName varchar(30) not null,
Address varchar(50) not null,
City varchar(30) not null,
Province char(2) not null Constraint ck_province check (Province Like '[A-Z][A-Z]') Constraint DF_Province Default 'AB',
PC char(7) not null Constraint CK_PostalCode Check (PC Like '[A-Z][0-9][A-Z] [0-9][A-Z][0-9]'),
PrePaidTip smallmoney not null Constraint ck_prepaidtip check (PrepaidTip >=0) Constraint DF_PrepaidTip Default 0,
RouteID int not null Constraint FK_ConsumerToDirection references Direction (DirectionID)
)
Create Table DeliveryType
(
DeliveryTypeID smallint not null Constraint PK_DelieverType primary key clustered,
DeliveryTypeDescription varchar(10) not null,
DeliveryTypeCharge smallmoney not null
)
Create Table Paper
(
PaperId smallint identity (1,1) not null Constraint PK_Paper primary key clustered,
PaperDescription varchar(30) not null
)
Create Table ConsumerPaper
(
ConsumerID int not null Constraint FK_ConsumerPaperToConsumer references Consumer (ConsumerId),
PaperID smallint not null Constraint FK_ConsumerPaperToPaper references Paper (PaperId),
DeliveryTypeID smallint not null Constraint FK_ConsumerPaperToDeliveryType references DeliveryType (DeliveryTypeId),
Constraint PK_ConsumerPaper_ConsumerID_PaperID primary key clustered (ConsumerID, PaperID)
)
CREATE PROCEDURE TransferHandler
(#HandlerIdOne INT = NULL,
#HandlerIdTwo INT = NULL,
#AreaID INT = NULL)
AS
-- guard clause - if something is wrong, call RAISERROR which
-- stops execution - no need to use "else" after that
IF #DHandleridone is NULL OR #Handleridtwo IS NULL OR #AreaID IS NULL
RAISERROR ('Missing parameter, please enter "id one" "id two" "area id" ', 16, 1)
BEGIN TRANSACTION
BEGIN TRY
-- update the first part
UPDATE dbo.handler
SET Salary = Salary - 25.00
WHERE handlerid = #HandlerIdOne
-- update the second part
UPDATE dbo.handler
SET Salary = Salary + 25.00
WHERE handlerid = #HandlerIdTwo
UPDATE dbo.handler
SET AreaID = null
WHERE handlerid = #HandlerIdOne
UPDATE dbo.handler
SET AreaID = #AreaID
WHERE handlerid = #HandlerIdTwo
-- if all goes well - commit the transaction
COMMIT TRANSACTION
END TRY
BEGIN CATCH
-- if an error occurred - show the error details
SELECT
ERROR_NUMBER() AS ErrorNumber,
ERROR_SEVERITY() AS ErrorSeverity,
ERROR_STATE() AS ErrorState,
ERROR_PROCEDURE() AS ErrorProcedure,
ERROR_LINE() AS ErrorLine,
ERROR_MESSAGE() AS ErrorMessage
-- roll back the transaction
ROLLBACK TRANSACTION
END CATCH
OK, so you could try something like this - using the TRY-CATCH feature available in SQL Server 2005 and newer:
CREATE PROCEDURE TransferHandler
(#HandlerIdOne INT = NULL,
#HandlerIdTwo INT = NULL,
#AreaID INT = NULL)
AS
-- guard clause - if something is wrong, call RAISERROR which
-- stops execution - no need to use "else" after that
IF #DHandleridone is NULL OR #Handleridtwo IS NULL OR #AreaID IS NULL
RAISERROR ('Missing parameter, please enter "id one" "id two" "area id" ', 16, 1)
BEGIN TRANSACTION
BEGIN TRY
-- update the first part
UPDATE dbo.handler
SET Salary = Salary - 25.00,
AreaId = NULL
WHERE handlerid = #HandlerIdOne
-- update the second part
UPDATE dbo.handler
SET Salary = Salary + 25.00,
AreaID = #AreaID
WHERE handlerid = #HandlerIdTwo
-- if all goes well - commit the transaction
COMMIT TRANSACTION
END TRY
BEGIN CATCH
-- if an error occurred - show the error details
SELECT
ERROR_NUMBER() AS ErrorNumber,
ERROR_SEVERITY() AS ErrorSeverity,
ERROR_STATE() AS ErrorState,
ERROR_PROCEDURE() AS ErrorProcedure,
ERROR_LINE() AS ErrorLine,
ERROR_MESSAGE() AS ErrorMessage
-- roll back the transaction
ROLLBACK TRANSACTION
END CATCH
Related
I've run into an issue a couple times now where I'll encase a query in BEGIN TRAN / ROLLBACK TRAN (so I can verify it works before committing any changes), and will get the error below. The BEGIN TRAN statement does not generate an error.
The ROLLBACK TRANSACTION request has no corresponding BEGIN TRANSACTION
The commands I was using the most recent time are below. I didn't save the errors at the time, but I believe that the UPDATE commands also errored because it didn't recognize ClientId as a valid column.
Each time it has done this, some statements have been rolled back, and others remained. In this case, I have neither a ClientId nor a ClientCode column.
I also can't perfectly recreate the initial run since running these outside of a transaction has caused me to lose all of my ClientCode fields, and the ClientId fields are not in the tables. Thankfully, none of the dev data was important, but because of its volume, it'll take me a little bit to repopulate.
Initially, I thought I'd just selected some of the query before running it, ommiting the BEGIN TRAN, so I reran it, careful to select everything and got the same error, as well as a host of others caused by the missing ClientCode field.
I'd like to know why this is happening so I can prevent it in the future.
EDIT: I did some additional testing on a later date and I have been unable to recreate this behavior. The transactions are being rolled back correctly, and the UPDATE command is not erroring for having an invalid column
BEGIN TRAN
ALTER TABLE tblInvoices ADD ClientId INT NULL
GO
UPDATE tblInvoices
SET ClientId = c.Id
FROM tblInvoices i
INNER JOIN Core.dbo.tblClients c
ON i.ClientCode = c.ClientCode
GO
ALTER TABLE tblInvoices ALTER COLUMN ClientId INT NOT NULL
GO
ALTER TABLE tblInvoices DROP COLUMN ClientCode
GO
ALTER TABLE tblClientSettings ADD ClientId INT NULL
GO
UPDATE tblClientSettings
SET ClientId = c.Id
FROM tblClientSettings cs
INNER JOIN Core.dbo.tblClients c
ON cs.ClientCode = c.ClientCode
GO
ALTER TABLE tblClientSettings ALTER COLUMN ClientId INT NOT NULL
GO
ALTER TABLE tblClientSettings DROP COLUMN ClientCode
GO
ROLLBACK TRAN
EDIT 2: It happened again on a small set of commands. The commands and the output messages are below.
Input:
BEGIN TRAN
CREATE TABLE tblEmailTemplates(
Id INT NOT NULL PRIMARY KEY IDENTITY(1, 1),
Subject NVARCHAR(2000) NULL,
Body NVARCHAR(MAX) NULL,
Sender NVARCHAR(200) NULL,
Recipients NVARCHAR(2000) NULL,
CC NVARCHAR(2000) NULL,
BCC NVARCHAR(2000) NULL,
Html BIT NULL
)
CREATE TABLE tblContactSeries (
Id INT NOT NULL PRIMARY KEY IDENTITY(1, 1),
AppId INT NOT NULL REFERENCES Foo_Apps.dbo.tblApps(Id),
Description NVARCHAR(200) NOT NULL
)
CREATE TABLE [dbo].tblEmails(
[Id] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY,
SeriesId INT NOT NULL REFERENCES tblContactSeries(Id),
TemplateId INT NULL REFERENCES tblEmailTemplates(Id),
TemplateParameters NVARCHAR(MAX) NULL,
[Sender] [nvarchar](200) NULL,
[Recipients] [nvarchar](2000) NULL,
[CC] [nvarchar](2000) NULL,
[BCC] [nvarchar](2000) NULL,
[Subject] [nvarchar](2000) NULL,
[Body] [nvarchar](max) NULL,
[Html] [bit] NOT NULL,
[ScheduledDate] [datetime] NOT NULL,
[OverdueDate] [datetime] NULL,
[Active] [bit] NOT NULL,
[Sent] [bit] NOT NULL,
[SendTime] [datetime] NULL,
[SendSuccess] [bit] NULL
)
CREATE TABLE [dbo].[tblAttachments](
[Id] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY,
EmailId [int] NOT NULL REFERENCES tblEmails(Id),
[FilePath] [nvarchar](2000) NULL,
[FileName] [nvarchar](200) NULL
)
GO
CREATE VIEW vwPendingAttachments AS
SELECT a.*
FROM tblAttachments a
INNER JOIN tblEmails e
ON a.EmailId = e.Id
WHERE e.Active = 1 AND e.Sent != 1
GO
ROLLBACK TRAN
Messages:
Msg 1763, Level 16, State 0, Line 23
Cross-database foreign key references are not supported. Foreign key 'Foo_Apps.dbo.tblApps'.
Msg 1750, Level 16, State 1, Line 23
Could not create constraint or index. See previous errors.
Msg 208, Level 16, State 1, Procedure vwPendingAttachments, Line 4 [Batch Start Line 59]
Invalid object name 'tblAttachments'.
Msg 3903, Level 16, State 1, Line 70
The ROLLBACK TRANSACTION request has no corresponding BEGIN TRANSACTION.
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;
So i designed a 'CD shop Database' and tried to write one query for all of it's elements but for some reason i can't create and add tables to that Database in one query. Here is my query :
CREATE DATABASE CDCI
ON PRIMARY(
Name = cddukkan_data,
FileName = 'C:\Program Files\Microsoft SQL Server\MSSQL14.VERITABANIM\MSSQL\DATA\cdci.mdf',
Size = 16 MB,
FileGrowth = 1 MB,
MaxSize = 1 GB
)
LOG ON(
Name = cddukkan_log,
FileName = 'C:\Program Files\Microsoft SQL Server\MSSQL14.VERITABANIM\MSSQL\DATA\cdci.ldf',
Size = 8 MB,
FileGrowth = 5%,
MaxSize = 512 MB
)
USE CDCI >An error occurs here
GO
CREATE TABLE Turler(
TurID INT IDENTITY(1, 1) NOT NULL,
TurAdi NVARCHAR(10) NOT NULL,
PRIMARY KEY(TurID),
UNIQUE(TurID)
)
CREATE TABLE Yonetmenler(
YonetmenID INT IDENTITY(1, 1) NOT NULL,
YonetmenAdi NVARCHAR(10) NOT NULL,
YonetmenSoyadi NVARCHAR(10) NULL,
DogumYili NCHAR(4),
CONSTRAINT DogumYili CHECK(DogumYili LIKE '19__' OR (DogumYili LIKE '20__' AND DogumYili < (YEAR(GETDATE()) - 18))),
Cinsiyet NCHAR(5),
CONSTRAINT Cinsiyet CHECK(Cinsiyet LIKE '[Ee]%' OR Cinsiyet LIKE '[Kk]%'),
PRIMARY KEY(YonetmenID),
UNIQUE(YonetmenID)
)
CREATE TABLE Raflar(
RafID INT IDENTITY(1, 1) NOT NULL,
RafTuru INT FOREIGN KEY REFERENCES Turler(TurID) NOT NULL,
PRIMARY KEY(RafID),
UNIQUE(RafID)
)
CREATE TABLE Filmler(
FilmID INT IDENTITY(1, 1) NOT NULL,
FilmAdi NVARCHAR(10) NOT NULL,
TurID INT FOREIGN KEY REFERENCES Turler(TurID) NOT NULL,
YonetmenID INT FOREIGN KEY REFERENCES Yonetmenler(YonetmenID) NOT NULL,
RafID INT FOREIGN KEY REFERENCES Raflar(RafID) NOT NULL,
Fiyat MONEY NOT NULL,
PRIMARY KEY(FilmID),
UNIQUE(FilmID)
)
CREATE TABLE Musteriler(
MusteriID INT IDENTITY(1, 1) NOT NULL,
MusteriAdi NVARCHAR(10) NOT NULL,
MusteriSoyadi NVARCHAR(10) NOT NULL,
Adresi NVARCHAR(20),
Telefon NVARCHAR(10),
CONSTRAINT Telefon CHECK(Telefon NOT LIKE '0%'),
PRIMARY KEY(MusteriID)
)
CREATE TABLE Oyuncular(
OyuncuID INT IDENTITY(1, 1) NOT NULL,
OyuncuAdi NVARCHAR(10) NOT NULL,
OyuncuSoyadi NVARCHAR(10) NULL,
DogumYili NCHAR(4),
CONSTRAINT DogumYili CHECK(DogumYili LIKE '19%' OR DogumYili < YEAR(GETDATE())),
PRIMARY KEY(OyuncuID),
UNIQUE(OyuncuID)
)
CREATE TABLE Satislar(
SatisID INT IDENTITY(1, 1) NOT NULL,
FilmID INT FOREIGN KEY REFERENCES Filmler(FilmID) NOT NULL,
MusteriID INT FOREIGN KEY REFERENCES Musteriler(MusteriID) NOT NULL,
SatisAdedi INT NOT NULL
)
CREATE TABLE FilmOyuncu(
FilmID INT FOREIGN KEY REFERENCES Filmler(FilmID) NOT NULL,
OyuncuID INT FOREIGN KEY REFERENCES Oyuncular(OyuncuID) NOT NULL
)
USE CDCI >An error occurs here
GO
CREATE TRIGGER [TelefonKontrol]
ON [Musteriler]
FOR INSERT
AS
DECLARE #tel NVARCHAR(10)
SELECT #tel = Telefon FROM INSERTED
IF #tel LIKE '0%'
BEGIN
PRINT 'Lütfen telefon numarasýný baþýna 0 rakamý koymayýnýz.'
ROLLBACK TRAN
END
GO
CREATE TRIGGER [FilmRafTuruUyumu]
ON [Filmler]
FOR INSERT
AS
DECLARE #filmTuru NVARCHAR(10)
DECLARE #rafTuru NVARCHAR(10)
DECLARE #rafID NVARCHAR(10)
SELECT #rafID = RafID FROM INSERTED
SELECT #filmTuru = TurID FROM INSERTED
SELECT #rafTuru = Raflar.RafTuru FROM INSERTED
INNER JOIN Raflar ON Raflar.RafID = #rafID
IF #rafTuru <> #filmTuru
BEGIN
PRINT 'Lütfen film uygun rafa yerleþtiriniz!'
ROLLBACK TRAN
END
GO
NOTE : I'm not new to the Database stuff because i got some classes of it but those were very basic level and theory-based classes. So you can consider me as 'starter'. Any helps, tips and suggestions are appriciated!
You need to check your location path for mdf and ldf files.
CREATE DATABASE CDCI
ON PRIMARY(
Name = cddukkan_data,
FileName = 'C:\Program Files\Microsoft SQL Server\MSSQL14.VERITABANIM\MSSQL\DATA\cdci.mdf',
Size = 16 MB,
FileGrowth = 1 MB,
MaxSize = 1 GB
)
LOG ON(
Name = cddukkan_log,
FileName = 'C:\Program Files\Microsoft SQL Server\MSSQL14.VERITABANIM\MSSQL\DATA\cdci.ldf',
Size = 8 MB,
FileGrowth = 5%,
MaxSize = 512 MB
)
go
USE CDCI -->An error occurs here
GO
CREATE TABLE Turler(
TurID INT IDENTITY(1, 1) NOT NULL,
TurAdi NVARCHAR(10) NOT NULL,
PRIMARY KEY(TurID),
UNIQUE(TurID)
)
CREATE TABLE Yonetmenler(
YonetmenID INT IDENTITY(1, 1) NOT NULL,
YonetmenAdi NVARCHAR(10) NOT NULL,
YonetmenSoyadi NVARCHAR(10) NULL,
DogumYili NCHAR(4),
CONSTRAINT DogumYili CHECK(DogumYili LIKE '19__' OR (DogumYili LIKE '20__' AND DogumYili < (YEAR(GETDATE()) - 18))),
Cinsiyet NCHAR(5),
CONSTRAINT Cinsiyet CHECK(Cinsiyet LIKE '[Ee]%' OR Cinsiyet LIKE '[Kk]%'),
PRIMARY KEY(YonetmenID),
UNIQUE(YonetmenID)
)
CREATE TABLE Raflar(
RafID INT IDENTITY(1, 1) NOT NULL,
RafTuru INT FOREIGN KEY REFERENCES Turler(TurID) NOT NULL,
PRIMARY KEY(RafID),
UNIQUE(RafID)
)
CREATE TABLE Filmler(
FilmID INT IDENTITY(1, 1) NOT NULL,
FilmAdi NVARCHAR(10) NOT NULL,
TurID INT FOREIGN KEY REFERENCES Turler(TurID) NOT NULL,
YonetmenID INT FOREIGN KEY REFERENCES Yonetmenler(YonetmenID) NOT NULL,
RafID INT FOREIGN KEY REFERENCES Raflar(RafID) NOT NULL,
Fiyat MONEY NOT NULL,
PRIMARY KEY(FilmID),
UNIQUE(FilmID)
)
CREATE TABLE Musteriler(
MusteriID INT IDENTITY(1, 1) NOT NULL,
MusteriAdi NVARCHAR(10) NOT NULL,
MusteriSoyadi NVARCHAR(10) NOT NULL,
Adresi NVARCHAR(20),
Telefon NVARCHAR(10),
CONSTRAINT Telefon CHECK(Telefon NOT LIKE '0%'),
PRIMARY KEY(MusteriID)
)
CREATE TABLE Oyuncular(
OyuncuID INT IDENTITY(1, 1) NOT NULL,
OyuncuAdi NVARCHAR(10) NOT NULL,
OyuncuSoyadi NVARCHAR(10) NULL,
DogumYili NCHAR(4),
CONSTRAINT DogumYili CHECK(DogumYili LIKE '19%' OR DogumYili < YEAR(GETDATE())),
PRIMARY KEY(OyuncuID),
UNIQUE(OyuncuID)
)
CREATE TABLE Satislar(
SatisID INT IDENTITY(1, 1) NOT NULL,
FilmID INT FOREIGN KEY REFERENCES Filmler(FilmID) NOT NULL,
MusteriID INT FOREIGN KEY REFERENCES Musteriler(MusteriID) NOT NULL,
SatisAdedi INT NOT NULL
)
CREATE TABLE FilmOyuncu(
FilmID INT FOREIGN KEY REFERENCES Filmler(FilmID) NOT NULL,
OyuncuID INT FOREIGN KEY REFERENCES Oyuncular(OyuncuID) NOT NULL
)
USE CDCI -->An error occurs here
GO
CREATE TRIGGER [TelefonKontrol]
ON [Musteriler]
FOR INSERT
AS
DECLARE #tel NVARCHAR(10)
SELECT #tel = Telefon FROM INSERTED
IF #tel LIKE '0%'
BEGIN
PRINT 'Lütfen telefon numarasýný baþýna 0 rakamý koymayýnýz.'
ROLLBACK TRAN
END
GO
CREATE TRIGGER [FilmRafTuruUyumu]
ON [Filmler]
FOR INSERT
AS
DECLARE #filmTuru NVARCHAR(10)
DECLARE #rafTuru NVARCHAR(10)
DECLARE #rafID NVARCHAR(10)
SELECT #rafID = RafID FROM INSERTED
SELECT #filmTuru = TurID FROM INSERTED
SELECT #rafTuru = Raflar.RafTuru FROM INSERTED
INNER JOIN Raflar ON Raflar.RafID = #rafID
IF #rafTuru <> #filmTuru
BEGIN
PRINT 'Lütfen film uygun rafa yerleþtiriniz!'
ROLLBACK TRAN
END
GO
This is my table:
CREATE TABLE [dbo].[tblVisitors] (
[Id] BIGINT IDENTITY (1, 1) NOT NULL,
[IP] NVARCHAR (100) NOT NULL,
[ProfileId] INT NULL,
[DateVisit] DATE NOT NULL,
[TimeVisit] TIME (0) NOT NULL,
[Browser] NVARCHAR (50) NOT NULL,
[UserOS] NVARCHAR (500) NOT NULL,
CONSTRAINT [PK_tblVisitors] PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT [FK_tblVisitors_tblProfile] FOREIGN KEY ([ProfileId]) REFERENCES [dbo].[tblProfile] ([Id]) ON DELETE SET NULL
);
I wrote a trigger to avoid redundancy:
CREATE TRIGGER [dbo].[Trigger_tblVisitors_OnInsert]
ON [dbo].[tblVisitors]
INSTEAD OF INSERT
AS
BEGIN
SET NoCount ON;
DECLARE #C INT;
SELECT *
INTO #TEMP
FROM inserted A
WHERE
NOT EXISTS (SELECT *
FROM tblVisitors B
WHERE (A.IP = B.IP)
AND (A.DateVisit = B.DateVisit)
AND (A.ProfileId = B.ProfileId));
IF (SELECT COUNT(*) FROM #TEMP) = 0
BEGIN
PRINT 'DUPLICATE RECORD DETECTED';
ROLLBACK TRANSACTION;
RETURN;
END
INSERT INTO tblVisitors (IP, ProfileId, DateVisit, TimeVisit, Browser, UserOS)
SELECT IP, ProfileId, DateVisit, TimeVisit, Browser, UserOS
FROM #TEMP;
END
But as this part of the code does not work, redundancy occurs:
(A.ProfileId = B.ProfileId)
Because after deleting this section, the operation is performed correctly. But this condition must be checked.
Using my psychic skills, I suspect that you have ProfileId values that are null, and in SQL the expression null = null is not true, but your logic requires it to be true.
Try this:
AND (A.ProfileId = B.ProfileId OR (A.ProfileId IS NULL AND B.ProfileId IS NULL))
I'm a newbie in SQL and I want to ask a specific question about the triggers. I have a table Purchases and I want to make an update to an other table with the same ID
CREATE TRIGGER tr_EmployeesSalaryPurchasesUpdate
ON Purchases
AFTER INSERT
AS
BEGIN
UPDATE EmployeesSalary
SET MonthlySalesMade = MonthlySalesMade + 1
WHERE EmployeeID = (SELECT DealMadeByEmployeeID FROM inserted)
END
based on the current inserted row.
But it doesn't seem to work (I don't get any errors).
My database
CREATE DATABASE RealEstateDatabase;
GO
USE RealEstateDatabase;
GO
CREATE TABLE Employees
(
EmployeeID INT IDENTITY NOT NULL PRIMARY KEY,
FirstName NVARCHAR(25) NOT NULL,
SecondName NVARCHAR(25) NOT NULL,
LastName NVARCHAR(25) NOT NULL,
NIN NVARCHAR(30) NOT NULL,--National Identification Number (ЕГН)
PhoneNumber NVARCHAR(20) NOT NULL,
Email NVARCHAR(50) NOT NULL,
[Address] NVARCHAR(50) NOT NULL,
CONSTRAINT UC_EmployeesNIN UNIQUE (NIN)
);
GO
CREATE TABLE GivingClients -- отдаващи клиенти(наемодатели и продавачи)
(
ClientID INT IDENTITY NOT NULL PRIMARY KEY,
ClientType NVARCHAR(20) NOT NULL,--Leaser(наемодател) or Seller
FirstName NVARCHAR(25) NOT NULL,
SecondName NVARCHAR(25),
LastName NVARCHAR(25) NOT NULL,
NIN NVARCHAR(30) NOT NULL,--National Identification Number (ЕГН)
PhoneNumber NVARCHAR(20) NOT NULL,
Email NVARCHAR(50),
[Town/Village] NVARCHAR(20),
[Address] NVARCHAR(50),
ServedByEmployeeID INT NOT NULL, -- по EmployeeID
CONSTRAINT FK_GivingClients_Employees
FOREIGN KEY (ServedByEmployeeID) REFERENCES Employees(EmployeeID),
CONSTRAINT CHK_GivingClients CHECK (ClientType IN('наемодател','продавач'))-- наемодател или продавач
);
GO
CREATE TABLE TakingClients -- приемащи клиенти (наематели и купувачи)
(
ClientID INT IDENTITY NOT NULL PRIMARY KEY,
ClientType NVARCHAR(20) NOT NULL,
FirstName NVARCHAR(25) NOT NULL,
SecondName NVARCHAR(25),
LastName NVARCHAR(25) NOT NULL,
NIN NVARCHAR(30) NOT NULL,--National Identification Number (ЕГН)
PhoneNumber NVARCHAR(20) NOT NULL,
Email NVARCHAR(50),
[Town/Village] NVARCHAR(20),
[Address] NVARCHAR(50),
ServedByEmployeeID INT NOT NULL, -- по EmployeeID
ServedByGivingClientID INT, -- връзка към отдаващите клиенти
CONSTRAINT FK_TakingClients_Employees
FOREIGN KEY (ServedByEmployeeID) REFERENCES Employees(EmployeeID),
CONSTRAINT FK_TakingClients_GivingClients
FOREIGN KEY (ServedByGivingClientID) REFERENCES GivingClients(ClientID),
CONSTRAINT CHK_TakingClients CHECK (ClientType IN('наемател', 'купувач'))
);
GO
CREATE TABLE EstatesBasicInfo
(
RealEstateID INT IDENTITY NOT NULL PRIMARY KEY,
RealEstateType NVARCHAR(20) NOT NULL,--бизнес имот, къща, апартамент, гараж
Area NVARCHAR(25) NOT NULL,--в квадратни метри
Architecture NVARCHAR(30), --панел, тухла и т.н.
Photos IMAGE,
OfferedByEmployeeID INT NOT NULL,
[OwnerID] INT NOT NULL,
CONSTRAINT FK_EstatesBasicInfo_GivingClients
FOREIGN KEY ([OwnerID]) REFERENCES GivingClients(ClientID),
CONSTRAINT FK_EstatesBasicInfo_Employees
FOREIGN KEY (OfferedByEmployeeID) REFERENCES Employees(EmployeeID)
);
GO
CREATE TABLE EstatesLocation
(
RealEstateLocationID INT NOT NULL PRIMARY KEY,
Country NVARCHAR(50) NOT NULL,
Region NVARCHAR(50) NOT NULL, --Област
[Town/Village] NVARCHAR(50) NOT NULL,
[Address] NVARCHAR(50) NOT NULL,
CONSTRAINT FK_EstatesLocation_EstatesBasicInfo
FOREIGN KEY (RealEstateLocationID) REFERENCES EstatesBasicInfo(RealEstateID)
);
GO
CREATE TABLE EstatesDetails
(
RealEstateDetailsID INT NOT NULL PRIMARY KEY,
Position NVARCHAR(11) NOT NULL,--изток, запад, север, юг, югоизток, югозапад, североизток, северозапад
Conditions NVARCHAR(15) NOT NULL, --добри или лоши
[Floor] INT NOT NULL, --етажът на който се намира или колко етажа има (в зависимост от видът на обекта)
Rooms INT NOT NULL,
CONSTRAINT CHK_EstateDetails CHECK (Position IN('изток', 'запад', 'север', 'юг', 'югоизток', 'югозапад', 'североизток', 'северозапад', 'всички') AND [Floor]>=0 AND Rooms>0),
CONSTRAINT FK_EstatesDetails_EstatesLocation
FOREIGN KEY (RealEstateDetailsID) REFERENCES EstatesLocation(RealEstateLocationID)
);
GO
CREATE TABLE EmployeesSalary
(
EmployeeID INT NOT NULL PRIMARY KEY,
CurrentSalary MONEY DEFAULT 0,-- на процент
MonthlySalesMade INT DEFAULT 0,
MonthlyRentsMade INT DEFAULT 0,
CONSTRAINT FK_EmployeesSalary_Employees
FOREIGN KEY (EmployeeID) REFERENCES Employees(EmployeeID),
CONSTRAINT CHK_EmployeesSalary
CHECK (CurrentSalary>=0 AND MonthlySalesMade>=0 AND MonthlyRentsMade>=0)
);
GO
CREATE TABLE Purchases
(
PurchaseID INT IDENTITY NOT NULL PRIMARY KEY,
DateBought SMALLDATETIME NOT NULL,
Price MONEY NOT NULL CHECK (Price>0),
RealEstateID INT UNIQUE NOT NULL,
DealMadeByEmployeeID INT NOT NULL,
CONSTRAINT FK_Purchases_EstatesBasicInfo
FOREIGN KEY (RealEstateID) REFERENCES EstatesBasicInfo(RealEstateID),
CONSTRAINT FK_Purchases_Employees
FOREIGN KEY (DealMadeByEmployeeID) REFERENCES Employees(EmployeeID)
);
GO
CREATE TABLE Rents
(
RentID INT IDENTITY NOT NULL PRIMARY KEY,
StartDate SMALLDATETIME,
EndDate SMALLDATETIME,
Price MONEY,
RealEstateID INT UNIQUE NOT NULL,
DealMadeByEmployeeID INT NOT NULL,
CONSTRAINT CHK_Rents CHECK (Price > 0 AND EndDate > StartDate),
CONSTRAINT FK_Rents_EstatesBasicInfo
FOREIGN KEY (RealEstateID) REFERENCES EstatesBasicInfo(RealEstateID),
CONSTRAINT FK_Rents_Employees
FOREIGN KEY (DealMadeByEmployeeID) REFERENCES Employees(EmployeeID)
);
Your trigger should work for a single insert. It is safer to write using IN:
CREATE TRIGGER tr_EmployeesSalaryPurchasesUpdate
ON Purchases AFTER INSERT
AS
BEGIN
UPDATE EmployeesSalary
SET MonthlySalesMade = MonthlySalesMade + 1
WHERE EmployeeID IN (SELECT DealMadeByEmployeeID FROM inserted)
END;
Or using JOIN:
CREATE TRIGGER tr_EmployeesSalaryPurchasesUpdate
ON Purchases AFTER INSERT
AS
BEGIN
UPDATE es
SET MonthlySalesMade = es.MonthlySalesMade + 1
FROM EmployeesSalary es JOIN
inserted i
ON es.EmployeeID = i.DealMadeByEmployeeID
END;
Note: If MonthlySalesMade is initialized to NULL rather than 0, then the expression should take the NULL into account:
SET MonthlySalesMade = COALESCE(es.MonthlySalesMade + 1, 1)