Trigger not firing for instead of insert SQL Server - sql

I am trying to create a trigger to convert a value from varchar to varbinary.
The creation of the trigger is successful. However it is not firing against an insert query.
Trigger code:
CREATE TRIGGER HashPassword
ON Users
INSTEAD OF INSERT
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO Users (Username, [Password], FirstName, LastName, RoleID)
SELECT
i.Username,
CONVERT(varbinary(max), EncryptByPassPhrase('iskam_6_za_bazata_moje_i_za_springa', i.[Password]), 2),
i.FirstName, i.LastName, i.RoleID
FROM
inserted AS i
END
Users table:
CREATE TABLE [dbo].[Users]
(
[Id] [int] IDENTITY(1,1) NOT NULL,
[Username] [varchar](255) NOT NULL,
[Password] [varbinary](max) NOT NULL,
[FirstName] [nvarchar](255) NOT NULL,
[LastName] [nvarchar](255) NOT NULL,
[RoleID] [int] NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
ALTER TABLE [dbo].[Users] WITH CHECK
ADD CONSTRAINT [FK_Users.RoleID]
FOREIGN KEY([RoleID]) REFERENCES [dbo].[Roles] ([Id])
GO
ALTER TABLE [dbo].[Users] CHECK CONSTRAINT [FK_Users.RoleID]
GO
I tried executing this query:
INSERT INTO Users (Username, [Password], FirstName, LastName, RoleID)
VALUES ('martini', 'parola', 'martin', 'atanasov', 4)
But the result was an error:
Implicit conversion from data type varchar to varbinary(max) is not allowed. Use the CONVERT function to run this query.

You can't insert a varchar into a varbinary max column. So this
INSERT INTO Users(Username,[Password],FirstName,LastName,RoleID)
VALUES('martini','parola','martin','atanasov',4)
should be
INSERT INTO Users(Username,[Password],FirstName,LastName,RoleID)
VALUES('martini', cast(N'parola' as varbinary(max)),'martin','atanasov',4)
Or you create a view on Users that performs the varbinary>nvarchar cast and put your instead of trigger on that.

Related

Write a trigger to update the columnB in TableB when the ColumnA in TableA are updated based on the common column in both the tables

CREATE TABLE [dbo].[USERS]
(
[USER_NAME] [nvarchar](64) NOT NULL,
[EMAIL_ADDRESS] [nvarchar](256) NULL,
[REGISTERED_DATE] [datetime] NOT NULL,
[FULL_NAME] [nvarchar](256) NOT NULL,
[MANAGER] [nvarchar](64) NULL,
[DEPARTMENT] [nvarchar](256) NULL,
[TITLE] [nvarchar](64) NULL,
PRIMARY KEY CLUSTERED ([USER_NAME] ASC)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
This is my table and I want the trigger to fire when the manager column is updated and the same values of the manage have to update on the another table based on the USER_NAME column.
i tried the the below trigger but it is not working.
Create TRIGGER [dbo].[UpdateManager]
ON [dbo].[USERS]
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;
declare #USER_NAME as nvarchar
declare #MANAGER as nvarchar
if(update(MANAGER))
begin
select #USER_NAME = USER_NAME from deleted
select #manager = Manager from deleted
update [dbo].[USERS_TEST] set MANAGER=#MANAGER where USER_NAME= #USER_NAME
end
END
You have two MAJOR issues in your trigger:
As mentioned in a comment, deleted can have multiple rows and you don't take that into account.
nvarchar has no length; the default in this case is a length of 1.
I suspect that the query you want is:
update ut
set MANAGER = d.MANAGER
from [dbo].[USERS_TEST] ut join
deleted d
on ut.USER_NAME = d.USER_NAME ;

How to insert IDENTITY column when creating table by this method (creating IDENTITY in table level)? [duplicate]

I have an existing table that I am about to blow away because I did not create it with the ID column set to be the table's Identity column.
Using SQL Server Management Studio, I scripted a "Create To..." of the existing table and got this:
CREATE TABLE [dbo].[History](
[ID] [int] NOT NULL,
[RequestID] [int] NOT NULL,
[EmployeeID] [varchar](50) NOT NULL,
[DateStamp] [datetime] NOT NULL,
CONSTRAINT [PK_History] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
My question is, how would I modify this SQL so that my resulting table has the ID column set as the Identity?
CREATE TABLE [dbo].[History](
[ID] [int] IDENTITY(1,1) NOT NULL,
[RequestID] [int] NOT NULL,
[EmployeeID] [varchar](50) NOT NULL,
[DateStamp] [datetime] NOT NULL,
CONSTRAINT [PK_History] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)
) ON [PRIMARY]
This has already been answered, but I think the simplest syntax is:
CREATE TABLE History (
ID int primary key IDENTITY(1,1) NOT NULL,
. . .
The more complicated constraint index is useful when you actually want to change the options.
By the way, I prefer to name such a column HistoryId, so it matches the names of the columns in foreign key relationships.
[id] [int] IDENTITY(1,1) NOT NULL,
of course since you're creating the table in SQL Server Management Studio you could use the table designer to set the Identity Specification.
Unique key allows max 2 NULL values. Explaination:
create table teppp
(
id int identity(1,1) primary key,
name varchar(10 )unique,
addresss varchar(10)
)
insert into teppp ( name,addresss) values ('','address1')
insert into teppp ( name,addresss) values ('NULL','address2')
insert into teppp ( addresss) values ('address3')
select * from teppp
null string , address1
NULL,address2
NULL,address3
If you try inserting same values as below:
insert into teppp ( name,addresss) values ('','address4')
insert into teppp ( name,addresss) values ('NULL','address5')
insert into teppp ( addresss) values ('address6')
Every time you will get error like:
Violation of UNIQUE KEY constraint 'UQ__teppp__72E12F1B2E1BDC42'. Cannot insert duplicate key in object 'dbo.teppp'.
The statement has been terminated.

How to insert Foreignkey value into a table which doesnt exist yet

I have a situation, I have two tables namely ,User and Company .
Here is my User table :
CREATE TABLE [dbo].[User](
[UserId] [int] IDENTITY(1,1) NOT NULL,
[UserName] [nvarchar](500) NOT NULL,
[Password] [nvarchar](500) NOT NULL,
[CompanyId] [int] NULL,
[LastModUserId] [int] NOT NULL,
[LastModDttm] [datetime] NOT NULL,
CONSTRAINT [PK_User] PRIMARY KEY CLUSTERED
(
[UserId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[User] WITH CHECK ADD CONSTRAINT [FK_User_Company] FOREIGN KEY([CompanyId])
REFERENCES [dbo].[Company] ([CompanyId])
GO
ALTER TABLE [dbo].[User] CHECK CONSTRAINT [FK_User_Company]
GO
ALTER TABLE [dbo].[User] WITH CHECK ADD CONSTRAINT [FK_User_User1] FOREIGN KEY([LastModUserId])
REFERENCES [dbo].[User] ([UserId])
GO
ALTER TABLE [dbo].[User] CHECK CONSTRAINT [FK_User_User1]
GO
Here is my Company Table :
CREATE TABLE [dbo].[Company](
[CompanyId] [int] IDENTITY(1,1) NOT NULL,
[CompanyName] [nvarchar](500) NOT NULL,
[Address1] [nvarchar](500) NULL,
[Address2] [nvarchar](500) NULL,
[LastModUserId] [int] NOT NULL,
[LastModDttm] [datetime] NOT NULL,
CONSTRAINT [PK_Company] PRIMARY KEY CLUSTERED
(
[CompanyId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[Company] WITH CHECK ADD CONSTRAINT [FK_Company_User] FOREIGN KEY([LastModUserId])
REFERENCES [dbo].[User] ([UserId])
GO
ALTER TABLE [dbo].[Company] CHECK CONSTRAINT [FK_Company_User]
GO
My problem :
I want to create a company record,I haven't created a user yet.When I Insert into the LastModUserId columun it will throw the error "Cannot Insert the value NULL into column 'LastModUserId' ,table MYDb.dbo.Company' , column does not allow nulls.INSERT fails.
If I try to insert a record into the User Table ,there is also the same problem ,there is CompanyId column,which doesn't allow nulls either
How do I handle this situation ?
Disable constraint to enter super record.
ALTER TABLE [User] NOCHECK CONSTRAINT [FK_User_User1];
GO
ALTER TABLE [User] NOCHECK CONSTRAINT [FK_User_Company];
GO
DECLARE #USERID AS INT, #COMPANYID AS INT;
SELECT #USERID = 1, #COMPANYID = 1;
SET IDENTITY_INSERT [User] ON;
INSERT INTO [User](
[UserId],
[UserName],
[Password],
[CompanyId],
[LastModUserId],
[LastModDttm]
)
select
#USERID,
'Super',
'Passw0rd',
1,
1,
getdate();
SET IDENTITY_INSERT [User] OFF;
SET IDENTITY_INSERT [Company] ON;
insert into [Company](
[CompanyId],
[CompanyName],
[Address1],
[Address2],
[LastModUserId],
[LastModDttm])
select
#COMPANYID,
'cOMANY a',
'Address 1',
'Address 2',
#USERID,
getdate();
SET IDENTITY_INSERT [Company] OFF;
go
ALTER TABLE [User] CHECK CONSTRAINT [FK_User_User1];
GO
ALTER TABLE [User] CHECK CONSTRAINT [FK_User_Company];
GO

use sql stored procedure to insert data which is returned from a query stored in a table

sql server 2005
I have a stored procedure which I used to insert data into a table. Some of the data will need to come from the results of executing a query that is stored in a separate table.
The main problem that I keep hitting is not being able to properly execute the returned query. I have tried creating several functions over the past couple of days based on other posts that I have read, but I keep hitting sql errors with exec, execute, sp_executesql, etc.
I am going to paste several scripts that you can use to replicate my environment. I am hoping that someone can please provide an actual code sample which will execute the returned query for use within the stored proc insert function.
Thank you!!!
CREATE TABLE [dbo].[CLIENT](
[cli_id] [int] IDENTITY(1,1) NOT NULL,
[cli_first_name] [varchar](100) NULL,
CONSTRAINT [PK__CLIENT__07F6335A] PRIMARY KEY CLUSTERED
(
[cli_id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
INSERT INTO CLIENT (cli_first_name, cli_last_name) values ('tom', 'smith');
go
CREATE TABLE [dbo].[ASSESSMENT_DATALABEL_LIST](
[adl_ID] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](50) NOT NULL,
[BoundName] [nvarchar](50) NOT NULL,
[Query] [ntext] NOT NULL,
[KeyFieldName] [nvarchar](50) NOT NULL,
[Status] [nvarchar](20) NOT NULL,
CONSTRAINT [PK_ASSESSMENT_DATALABEL_LIST] PRIMARY KEY CLUSTERED
(
[adl_ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
INSERT INTO ASSESSMENT_DATALABEL_LIST (Name, BoundName, Query, KeyFieldName, Status)
values ('Name, First', 'cli_first_name', 'select IsNull(cli_first_name,'''') as cli_first_name FROM CLIENT WHERE cli_id = #KeyFieldValue', 'cli_ID', 'Active')
go
INSERT INTO ASSESSMENT_DATALABEL_LIST (Name, BoundName, Query, KeyFieldName, Status)
values ('Name, Last', 'cli_last_name', 'select IsNull(cli_last_name,'''') as cli_last_name FROM CLIENT WHERE cli_id = #KeyFieldValue', 'cli_ID', 'Active')
go
CREATE TABLE [dbo].[Item_Source]
(
[Item_ID] [int] IDENTITY(1,1) NOT NULL,
[ItemType] [nvarchar](50) NOT NULL,
[ItemCaption] [nvarchar] (50) NULL,
[adl_ID] [int] NOT NULL
)
go
INSERT INTO Item_Source
(ItemType, ItemCaption, adl_ID) values
('DATALABEL', 'First Name',1)
go
INSERT INTO Item_Source
(ItemType, ItemCaption, adl_ID) values
('DATALABEL', 'Last Name',2)
go
CREATE TABLE [dbo].[Item_Destination]
(
[ItemType] [nvarchar](50) NOT NULL,
[ItemCaption] [nvarchar] (50) NULL,
[ItemValue] [nvarchar](50) NULL
)
go
CREATE PROCEDURE [dbo].[spInsertStuff]
#cli_id int
AS
INSERT INTO Item_Destination
(ItemType, ItemCaption, ItemValue)
SELECT
ItemType, ItemCaption, [[[ VALUE OF EXECUTED QUERY FROM ADL TABLE --- dbo.FunctionToGetResultsOfStoredQuery(Item_Source.adl_id, #cli_id) ]]]
FROM Item_Source WHERE Item_Source.Item_ID IN (1,2)
-- this insert will insert both Item_Source rows into Item_Dest with one call. The first row should have an ItemValue of Tom, the second row should have an ItemValue of Smith
GO
You may check this fiddle
The code of the Stored Procedure is:
CREATE PROCEDURE [dbo].[spInsertStuff]
#cli_id int
AS
DECLARE #SQL AS VARCHAR(MAX)
DECLARE #ADL_ID AS INT
DECLARE MyCURSOR
CURSOR FOR
SELECT QUERY, ADL_ID FROM ASSESSMENT_DATALABEL_LIST
OPEN MyCURSOR
FETCH NEXT FROM MyCURSOR INTO #SQL, #ADL_ID
WHILE ##FETCH_STATUS = 0
BEGIN
SET #SQL = REPLACE(#SQL,'#KeyFieldValue',#cli_id)
DECLARE #Temp AS TABLE ([Value] [nvarchar](50))
INSERT INTO #Temp
EXEC (#SQL)
INSERT INTO Item_Destination
(ItemType, ItemCaption, ItemValue)
SELECT
ItemType, ItemCaption, (SELECT [Value] FROM #Temp)
FROM Item_Source
WHERE Item_Source.adl_ID = #ADL_ID
DELETE FROM #Temp
FETCH NEXT FROM MyCURSOR INTO #SQL, #ADL_ID
END
CLOSE MyCURSOR
DEALLOCATE MyCURSOR
GO

SQL Lookup List

I have been asked to create a table in SQL and am not sure about one of the table fields.
I have been asked to create a table with the following information:
First Name
Last Name
Three Address Lines
Mobile Phone
Home Phone
Date Modified
Person Category
Comment
This is the description for the Person Category:
Person Category:
Simple Lookup List contained in the database, (ID and Description), can pre-populate this data from the script, no need to edit and update from the VB application. Category descriptions are: Client, Worker, Assessor, and Unknown.
Can someone please explain to me what is needed here?
UPDATE
Here is my current script for the Person table:
CREATE TABLE db_person.Person
(
PersonID NUMBER NOT NULL,
FirstName varchar(50) NOT NULL,
LastName varchar(50) NOT NULL,
AddressLine1 varchar(50),
AddressLine2 varchar(50),
AddressLine3 varchar(50),
MobilePhone varchar(20),
HomePhone varchar(20),
DateModified DATE,
PersonCategory varchar(50),
Comment varchar(8000),
PRIMARY KEY (PersonID)
)
Can I have some help to create the Lookup List for the PersonCategory and to link it into the Person Table?
It means that you need to create another table for the Person Category. Thus a one-to-many relationship between the 2 tables.
Moreover because the description of a person is limited to either Client, Worker, Assessor or Unknown, you should be handle this in your script creation by using the keyword "CHECK".
i.e.
CHECK (Description in ("Client", "Worker", "Assessor", "Unknown"))
First of all you must create the Categories lookup table. You could create it with a script like this:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [Categories](
[Id] [uniqueidentifier] ROWGUIDCOL NOT NULL,
[Description] [varchar](50) NOT NULL,
CONSTRAINT [PK_Categories] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING ON
GO
ALTER TABLE [Categories] ADD CONSTRAINT [DF_Categories_Id] DEFAULT (newid()) FOR [Id]
GO
and populate it with the 4 descriptions:
INSERT INTO Categories ([Description])
VALUES ('Client')
INSERT INTO Categories ([Description])
VALUES ('Worker')
INSERT INTO Categories ([Description])
VALUES ('Assessor')
INSERT INTO Categories ([Description])
VALUES ('Unknown')
After that, you must create the Persons table, with the constraint with the Categories table:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [Persons](
[Id] [uniqueidentifier] ROWGUIDCOL NOT NULL,
[IdCategory] [uniqueidentifier] NOT NULL,
[FirstName] [varchar](50) NOT NULL,
[LastName] [varchar](50) NOT NULL,
[FirstAddress] [varchar](250) NULL,
[SecondAddress] [varchar](250) NULL,
[ThirdAddress] [varchar](250) NULL,
[HomePhone] [varchar](50) NULL,
[MobilePhone] [varchar](50) NULL,
[Modified] [datetime] NOT NULL,
[Comment] [varchar](500) NULL,
CONSTRAINT [PK_Persons] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING ON
GO
ALTER TABLE [Persons] ADD CONSTRAINT [DF_Persons_Id] DEFAULT (newid()) FOR [Id]
GO
ALTER TABLE [Persons] WITH CHECK ADD CONSTRAINT [FK_Persons_Categories] FOREIGN KEY([IdCategory])
REFERENCES [Categories] ([Id])
GO
ALTER TABLE [Persons] CHECK CONSTRAINT [FK_Persons_Categories]
GO
Now you have the two tables :)
These scripts run on Microsoft SQL Server.
PS: Best practice is to do another table for multiple addresses and multiple phones ;)
To retrieve data with the SELECT, you could do:
SELECT FirstName, LastName, Description AS Category
FROM Persons INNER JOIN
Categories ON Categories.Id = Persons.IdCategory
If you're using NUMBER for the IDs, change the IdCategory datatype in NUMBER. After that, the storedprocedure could be like:
CREATE PROCEDURE [AddPerson]
(
#Category varchar(50),
#FirstName varchar(50),
#LastName varchar(50),
#FirstAddress varchar(250) = NULL,
#SecondAddress varchar(250) = NULL,
#ThirdAddress varchar(250) = NULL,
#HomePhone varchar(50) = NULL,
#MobilePhone varchar(50) = NULL,
#Comment varchar(500) = NULL
)
AS BEGIN
Declare #idCategory NUMBER
Set #idCategory = SELECT Id FROM Categories WHERE Description = Category
INSERT INTO Persons ([IdCategory], [FirstName], [LastName],
[FirstAddress],
[SecondAddress],
[ThirdAddress],
[HomePhone],
[MobilePhone],
[Modified],
[Comment])
VALUES (#idCategory,
#FirstName,
#LastName,
#FirstAddress,
#SecondAddress,
#ThirdAddress,
#HomePhone,
GETDATE(),
#MobilePhone,
#Comment)
END
GO
I'm sorry if this codes contains some errors but I wrote it with notepad :)