I am getting the Invalid object name 'CUSTOMER_temp'. Error code. I made these two tables and made the temporary table. Also when I put state from inserted. It gives me the error code Invalid column name 'state'. I am not sure if I need this still or if I am able to get rid of it.
The purpose of this trigger is to automatically copy new records to a new table.
DROP TABLE CUSTOMER
CREATE TABLE CUSTOMER
(
CustomerID CHAR(5) PRIMARY KEY, --Make Primary Key
CustLastName VARCHAR(20),
CustFirstName VARCHAR(20),
CustStreet VARCHAR(60),
CustCity VARCHAR(30),
CustState CHAR(2),
CustZip CHAR(5),
CustPhone CHAR(10),
CustEmail CHAR(50),
);
drop table CUSTOMER_temp
CREATE TABLE CUSTOMER_temp -- temporary table
(
CustomerID CHAR(5) PRIMARY KEY,
CustLastName VARCHAR(20),
CustFirstName VARCHAR(20),
CustStreet VARCHAR(60),
CustCity VARCHAR(30),
CustState CHAR(2),
CustZip CHAR(5),
CustPhone CHAR(10),
CustEmail CHAR(50),
);
CREATE TRIGGER dbo.CustCopy
On CUSTOMER
AFTER INSERT
AS
BEGIN
SET NOCOUNT ON;
insert CUSTOMER_temp (CustomerID, CustLastName, CustPhone, CustState)
Select CustomerID, CustLastName, CustPhone, CustState from inserted
END
Try this... You need INTO after the Insert.
UPDATE removed dbo.
CREATE TRIGGER dbo.CustCopy
On CUSTOMER
AFTER INSERT
AS
BEGIN
SET NOCOUNT ON;
insert INTO CUSTOMER_temp (CustomerID, CustLastName, CustPhone, CustState)
Select CustomerID, CustLastName, CustPhone, CustState from inserted
END
Related
I have a table with a uniqueidentifier and NEWID() default for new records. Executed the insert script. How do I know what uniqueidentifier was generated for the Id column since the last insert?
Table Script
CREATE TABLE [dbo].[MyData](
[Id] [uniqueidentifier] NOT NULL,
[Data] [varbinary](max) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
ALTER TABLE [dbo].[MyData] ADD CONSTRAINT [DF_MyData_Id] DEFAULT (newid()) FOR [Id]
GO
Insert Script
INSERT INTO dbo.MyData (Data)
VALUES (NULL)
GO
What is the uniqueidentifier was inserted?
Use an OUTPUT clause. I INSERT the data into a table variable so that is it can consumed by other statements afterwards:
DECLARE #IDs table (ID uniqueidentifier);
INSERT INTO dbo.MyData
OUTPUT inserted.Id
INTO #IDs
DEFAULT VALUES;
SELECT *
FROM #IDs;
There is no particular value in relying on the default in your example.
Just create a scalar variable of type uniqueidentifier and assign it the result of NEWID yourself
DECLARE #Id UNIQUEIDENTIFIER = NEWID();
INSERT INTO dbo.MyData (Id)
VALUES (#Id);
This is more concise than having to insert into a table variable and subsequently select from it.
I have an error when loading a procedure telling me
Cannot insert the value NULL into column 'requestID', table 'MCAST.a01.tbl_enrollmentRequests'; column does not allow nulls. INSERT fails.
Now requestID is a UNIQUEIDENTIFIER type of variable. Is UNIQUEIDENTIFIER an auto generated number or not? Below is a sample of my code where you can see requestID.
CREATE PROCEDURE [a01].[usp_auditAcceptRequest]
(#AccountID UNIQUEIDENTIFIER,
#GroupID UNIQUEIDENTIFIER,
#Reason NVARCHAR(45)
)
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO [a01].[tbl_enrollmentRequests] (requestDate, groupID, accountID)
VALUES (SYSDATETIMEOFFSET(), #GroupID, #AccountID)
DECLARE #RequestID UNIQUEIDENTIFIER
SET #RequestID = (SELECT requestID
FROM [a01].tbl_enrollmentRequests
WHERE groupID = #GroupID AND accountID = #AccountID)
INSERT INTO [a01].[tbl_enrollmentAudits] (entryDate, requestID, groupID, accountID, accepted, reason)
VALUES (SYSDATETIMEOFFSET(), #RequestID, #GroupID, #AccountID, 1, #Reason)
DELETE FROM [a01].[tbl_enrollmentRequests]
WHERE requestID = #RequestID
END;
GO
Here is where I am implementing the above procedure
BEGIN
DECLARE #AccountID UNIQUEIDENTIFIER;
DECLARE #GroupID UNIQUEIDENTIFIER;
(SELECT #AccountID = accountID
FROM [a01].[tbl_userAccounts] WHERE accountUsername='saraht');
(SELECT #GroupID = groupID FROM [a01].[tbl_groups] WHERE groupName LIKE '%Foo%');
EXECUTE [a01].[usp_addRequest] #AccountID, #GroupID;
END;
GO
Thanks for your help !!
A uniqueidentifier is a normal column, and if you want to have a automatically assigned value you need to add a default to the column. Typically the functions used for the default are newid() or newsequentialid().
Edit based on the posted table definition; you could use this:
CREATE TABLE [a01].[tbl_enrollmentRequests](
requestID UNIQUEIDENTIFIER PRIMARY KEY DEFAULT (NEWID()),
requestDate DATETIMEOFFSET NOT NULL,
groupID UNIQUEIDENTIFIER REFERENCES [a01].[tbl_groups] (groupID) NOT NULL,
accountID UNIQUEIDENTIFIER REFERENCES [a01].[tbl_userAccounts] (accountID) NOT NULL
);
That being said, you can also pre-generate a uniqueidentifier and assign that to a variable in the stored procedure prior to insertion, since the generated GUID can be assumed not to collide with any existing GUID. The benefit of this is that you know the id of the inserted row even without retrieving it from an OUTPUT clause.
A notice on performance: a significant number of rows with a clustered primary key of random GUIDs (as generated bynewid()) are a performance issue, since the inserts will cause many page splits to occur due to the randomness. The newsequentialid() function pretty much completely resolves the performance problem, but it makes the generated GUIDs guessable, so that this can only be used when "random" IDs are not required.
Is UNIQUEIDENTIFIER an auto generated number or not?
What do you ask us? You have a look at the table definition and see whether a default that sets a new uniqueidentifier is defined or not.
If it is not - then no.
If you try to insert null, then also not (as your insert overrides the default value).
---Edit:
As per the table definition you posted:
requestID UNIQUEIDENTIFIER PRIMARY KEY
no default value defined that sets it. So no.
This is my insert statement that I am currently using. The primary key in this table is IDNumber
ALTER procedure [dbo].[AddCustomer]
#IDNumber nvarchar(20),
#Title nchar(10),
#Name nvarchar(50),
#Surname nvarchar(50),
#CellPhone nchar(10),
#AddressLine1 nvarchar(50),
#Suburb nvarchar(40),
#City nvarchar(30),
#PostalCode nchar(10),
#EmailAddress nvarchar(50),
#Password nvarchar(20)
as
insert into Customer(IDNumber,Title,Name,Surname,CellPhone,AddressLine1,Suburb,City,PostalCode,EmailAddress,[Password])
values (#IDNumber,#Title,#Name,#Surname,#CellPhone,#AddressLine1,#Suburb,#City,#PostalCode,#EmailAddress,#Password)
Now I would like the sql statement that will prevent a duplicate email address from being inserted.
You want to look at unique constraints http://msdn.microsoft.com/en-gb/library/ms190024.aspx
ALTER TABLE Customer
ADD CONSTRAINT UC_email UNIQUE (EmailAddress);
GO
That should actually be a constraint on the table column.
ALTER TABLE Customer
ADD CONSTRAINT EmailAddress_Uniqueness_Constraint UNIQUE (EmailAddress)
You can create unique index/key on Email column.
CREATE UNIQUE INDEX IX_Email ON TABLE(EMAIL);
I'm trying to insert into two tables at the same time via stored procedure but it writes to only one table and fail to the other.
ALTER PROCEDURE [dbo].[insert_emp_pics]
#EmpName nvarchar(100),
#Nationality nvarchar(30),
#PassportPic nvarchar(100),
#Pic nvarchar(100)
AS
Begin
set nocount on;
DECLARE #ID int,
#Emp_ID int
insert into Employee (EmpName,Nationality)
values (#EmpName,#Nationality)
select #ID = ##IDENTITY
insert into DatePics
(PassportPic,Pic)
values
(#PassportPic ,#Pic)
select #Emp_ID = ##IDENTITY
end
There is relation between two tables
first table [Employee] PK ID
second table [DatePics] FK Emp_ID
this is the error message after executing this statement.
Cannot insert the value NULL into column 'Emp_ID', table 'QTecTest.dbo.DatePics';
column does not allow nulls. INSERT fails.
You need to insert the new Emp_Id as a Foreign Key to DatePics (and assuming both tables have identity columns):
insert into Employee (EmpName,Nationality)
values (#EmpName,#Nationality);
set #EMP_ID = SCOPE_IDENTITY();
insert into DatePics (PassportPic,Pic, Emp_ID)
values (#PassportPic ,#Pic, #EmpID);
set #DatePicsID = SCOPE_IDENTITY();
Also, please use SCOPE_IDENTITY over ##IDENTITY - ##Identity is vulnerable to issues where a Trigger also creates an new (unrelated) identity.
A column declared as primary key cannot have NULL values.
In your stored procedure you are not supplying value to Emp_ID column and so Insert fails.
If you want to automatically insert values in that column make it as IDENTITY column also
This is what I have
CREATE TABLE Saver(
SaverID INT NOT NULL PRIMARY KEY IDENTITY,
FirstName VARCHAR(10),
Surname VARCHAR(10),
[Address] VARCHAR(60),
Email VARCHAR(30),
Username VARCHAR(10),
[Password] VARCHAR(10),
CreditBalance INT,
);
I'm trying to insert data into my table with this:
INSERT INTO Customer
(SaverID,FirstName,Surname,[Address],Email,Username,[Password],CreditBalance)
VALUES (01,'David','Slavic','123 fake street','David#gmail.com','DJ','passcode',10.00);
I get this error:
Msg 544, Level 16, State 1, Line 1
Cannot insert explicit value for identity column in table 'Customer' when IDENTITY_INSERT is set to OFF.
I don't understand why? Please help
You should not insert value for SaverID, you have told the RDBMS to generate a value for it (you've done so with your CREATE statement): SaverID INT NOT NULL PRIMARY KEY IDENTITY.
Your primary key is auto increment, you can not insert a value on it
Omit the ID from your INSERT query:
INSERT INTO Customer
(FirstName,Surname,[Address],Email,Username,[Password],CreditBalance)
VALUES ('David','Slavic','123 fake street','David#gmail.com','DJ','passcode',10.00);