Get last identity of table and insert to new table - sql-server

I'm trying to get the last identity from my table 'usergold' and insert it in a new table table with insert value. I used select "IDENT_CURRENT('UserGold') As userid", new value should be in userid.
But I'm getting an error when I put it in insert, I cannot create the trigger. Please check my code.
create trigger addrole
on UserGold
after Insert
as
Begin
select IDENT_CURRENT('UserGold') As userid
insert into AspNetUserRoles values(userid,'2c258e8d-c648-4b38-9b01-989d4dd525fe')
end
i tried
create trigger addrole
on UserGold
after Insert
as
Begin
declare
#userid nvarchar(50)
select #userid=userId from UserGold where userId=IDENT_CURRENT('UserGold')
insert into AspNetUserRoles(UserId,RoleId) values(#userid,'2c258e8d-c648-4b38-9b01-989d4dd525fe')
end
igot this error "Error converting data type nvarchar to numeric " from
select #userid=userId from UserGold where userId=IDENT_CURRENT('UserGold')

Your INSERT statement is not written correctly.
Try
INSERT INTO AspNetUserRoles ( [col_1_name], [col_2_name] )
VALUES (
( SELECT IDENT_CURRENT ( 'UserGold' ) ),
'2c258e8d-c648-4b38-9b01-989d4dd525fe'
);
Note: Replace the column holder names ( col_1_name, col_2_name ) with the actual column names being inserted to.

Related

Compare two KeyValue types data in SQL Server 2012

I have the below data available in a table
DECLARE #AddressTbl As Table (ID int identity,Address varchar(100))
INSERT INTO #AddressTbl
VALUES ('State:AndhraPradesh,Dist:Prakasam')
Next time when I enter the same value I should be notified that this value exists in the table.
For this I will use an sp with warning message that the data is available. But I want how to implement the logic to compare the data.
Create Procedure usp_InsertAddress
(
#Address varchar(100)
)
AS
DECLARE #ID INT
SELECT #ID=(SELECT ID FROM #AddressTbl WHERE Address = #Address)
IF #ID IS NULL
BEGIN
INSERT INTO #AddressTbl
VALUES ('State:AndhraPradesh,Dist:Prakasam')
END;
I may enter the address like 'Dist:Prakasam,State:AndhraPradesh'
and there may be some blank spaces also. So need to parse the address and check the key and values.
I will use permanent table instead of table variable.
Appreciate your help.
You can use if exists for check. Or you can add unique CONSTRAINT in your table. The UNIQUE constraint ensures that all values in a column are different. This will return error if you are trying to insert duplicate value.
Create Procedure usp_InsertAddress
(
#Address varchar(100)
)
AS
if exists(SELECT ID FROM #AddressTbl WHERE Address = #Address)
begin
select 'Value is Already Exist in Table'---For Warning
end
else
BEGIN
INSERT INTO #AddressTbl
VALUES ('State:AndhraPradesh,Dist:Prakasam')
select 'Value Inserted Sucessful'---For Success
END;

Trigger ON Table which fire INSERT into another table which has NOT NULL constraint , which has float datatype

CREATE TRIGGER studenttr ON tstudentlog
AFTER INSERT
AS
BEGIN
INSERT INTO TABLE tstudent(sname, marks)
SELECT sname,marks FROM INSERTED
END
The structure of tstudent
CREATE TABLE tstudent
(
name VARCHAR(20),
marks FLOAT NOT NULL
)
ALTER TABLE tstudent ADD DEFAULT (0) FOR marks
When I don't pass data in the marks column WHILE INSERTING record into tstudentlog
I get an error:
Cannot insert the value NULL into column 'marks', table 'tstudent'; column does not allow nulls. INSERT fails. The statement has been terminated.
I tried the following but did not work
INSERT INTO TABLE tstudent(sname)
SELECT sname
FROM INSERTED
where marks is null;
I wanted to pass NULL Values tstudent table AND wanted those situdation to be handled by 'DEFAULT VALUES kept in tstudent'
How can I achieve that?
I had a lot of problem with default values in table,
It could go well to use coalesce on insert statement?
CREATE TRIGGER studenttr ON tstudentlog
AFTER INSERT
AS
BEGIN
INSERT INTO TABLE tstudent(sname, marks)
SELECT sname,coalesce(marks,0) FROM INSERTED
END

INSERT and UPDATE after one row inserted MS SQL

I don't know if I'm thinking correct, so I'm open for suggestions.
I'm using MS SQL SERVER 2008 R2.
Here is the 'story'
Everytime someone insert a row into tblDelivered there is a trigger that insert in tblConditionDel five values(1,1,1,1,1). This is a table with an auto ID increment. And for that inserted row must fieldname ConditionID be updated with the ID from tblConditionDel.
I think there is something wrong with my where statement
If I delete the where statement the ID is update for the entire table, but it must be for the one inserted row.
My code:
ALTER TRIGGER [dbo].[trgCond2] ON [dbo].[tblDelivered]
AFTER INSERT
AS
insert into tblConditionDel(Con1,Con2,Con3,Con4, Con5)
values(1,1,1,1,1);
update tblDelivered set ConditionID = (select max(ConditionID) from tblConditionDel)
where (select 1 from inserted) = tblDelivered.ConditionID
Thx in advance
Your solution does not work if more than one row is inserted.
Do like this
CREATE TABLE tblDelivered (
DeliveredID int NOT NULL
,ConditionID int
);
CREATE TABLE tblConditionDel (
ConditionID int IDENTITY(1,1)
,Con1 int NOT NULL
,Con2 int NOT NULL
,Con3 int NOT NULL
,Con4 int NOT NULL
,Con5 int NOT NULL
);
CREATE TRIGGER [dbo].[trgCond2] ON [dbo].[tblDelivered]
AFTER INSERT
AS
SET NOCOUNT ON;
DECLARE #ConditionIDs AS table ( -- stores inserted conditionsIDs
DeliveredID int NOT NULL
,ConditionID int NOT NULL
);
MERGE INTO tblConditionDel -- INSERT does not support OUTPUT INTO for multiple rows
USING inserted AS triggerinserted
ON 1 = 0
WHEN NOT MATCHED THEN
INSERT (Con1, Con2, Con3, Con4, Con5)
VALUES (1,1,1,1,1)
OUTPUT triggerinserted.DeliveredID
,inserted.ConditionID
INTO #ConditionIDs;
UPDATE tblDelivered
SET ConditionID = ConditionIDs.ConditionID
FROM tblDelivered
INNER JOIN #ConditionIDs AS ConditionIDs
ON ConditionIDs.DeliveredID = tblDelivered.DeliveredID
-- Test code
INSERT INTO tblDelivered (DeliveredID)
VALUES (4),(5),(6);
SELECT * FROM tblConditionDel
SELECT * FROM tblDelivered
You would want to do something like this:
ALTER TRIGGER [dbo].[trgCond2] ON [dbo].[tblDelivered]
AFTER INSERT
AS
declare #new_id int, #delivered_id int
set #delivered_id = (select ConditionID from inserted) -- captures id from inserted table
insert into tblConditionDel(Con1,Con2,Con3,Con4, Con5)
values(1,1,1,1,1);
set #new_id = scope_identity() -- captures new id from tblCondition into a variable
update tblDelivered set ConditionID = #new_id -- set new tblcondition id
where ConditionID = #delivered_id -- for the record that matches the inserted one

SQL Server : Triggers for Insert

create table tab(id int identity,task_id int,task_descp varchar(10),task_code varchar(10))
insert into tab values(7,'BUS','B')
insert into tab values(3,'CAR','C')
create table tab_detail( task_descp varchar(10),task_code varchar(10),color varchar(10))
create trigger tab_trigger on tab for insert as
declare #task_descp varchar(10)
declare #task_code varchar(10)
declare #task_id int
set #task_descp=i.task_descp from inserted i
set #task_code=i.task_code from inserted i
set #task_id=i.task_id from inserted i
if(#task_id=7)
insert into tab_detail values(#task_descp,#task_code,'BLUE')
if(#task_id=3)
insert into tab_detail values(#task_descp,#task_code,'GREEN')
go
I want to create a trigger for table tab where if I insert a record based on the task_id column a record has to be inserted into another table tab_detail.
When executing this I get this error:
Incorrect syntax near the keyword 'from'
Instead of:
set #task_descp=i.task_descp from inserted i
Try this:
select #task_descp=i.task_descp from inserted i
Or you could do this:
create trigger tab_trigger on tab for insert as
insert into tab_detail
select task_descp, task_code, case #task_id when 7 then 'BLUE' else 'GREEN' end
from inserted
where taskid in (7,3)
go
Change the SET to SELECT. Also, inserted is a recordset, not a single value. Fixing the code issue still might result in a run time issue!
This code should work fine for a recordset of information.
CREATE TRIGGER tab_trigger ON tab FOR INSERT AS
BEGIN
-- nothing to do?
IF (##rowcount = 0) RETURN;
-- do not count rows
SET NOCOUNT ON;
-- inserted data
INSERT INTO tab_detail
SELECT
i.task_descp,
i.task_code,
CASE i.taskcode
WHEN 7 THEN 'BLUE'
WHEN 3 THEN 'GREEN'
ELSE ''
END
FROM inserted i
WHERE i.task_code in (3, 7)
END
GO

SQL Server check constraint failing on correct input

I'm using a check constraint on a table to restrict what values are inserted in the table..
Here's an explanation of what I'm trying to do
If any Product(sedan) is associated to a specific ObjLevel (Toyota) then the same Product cannot be associated to another specific ObjLevel (Lexus)
After I apply the check constraint on the table, any insert containing ObjLevel "toyota" or "lexus" fails..
create table ObjLevel(
OLID int identity,
Name varchar(50) not null
)
insert into ObjLevel values('Ford')
insert into ObjLevel values('Toyota')
insert into ObjLevel values('Lexus')
insert into ObjLevel values('GM')
insert into ObjLevel values('Infiniti')
create table ObjInstance(
OLIID int identity (20,1),
OLID int
)
insert into ObjInstance values(1)
insert into ObjInstance values(2)
insert into ObjInstance values(3)
insert into ObjInstance values(4)
insert into ObjInstance values(5)
create table Product(
PID int identity(50,1),
Name varchar(20)
)
insert into Product values ('sedan')
insert into Product values ('coupe')
insert into Product values ('hatchback')
create table ObjInstanceProd(
OLIID int,
PID int
)
create FUNCTION [dbo].[fnObjProd] (#Pid int) RETURNS bit WITH EXECUTE AS CALLER AS
BEGIN
DECLARE #rv bit
DECLARE #cnt int
SET #cnt = 0
SET #rv = 0
SET #cnt=
(Select Count(*) from ObjInstanceProd olip
join ObjInstance oli
on olip.OLIID = oli.OLIID
join ObjLevel ol
on ol.OLID = oli.OLID
where ol.Name in ('Toyota','Lexus')
and PID = #Pid)
if(#cnt>0)
SET #rv = 1
RETURN #rv
END
ALTER TABLE [dbo].[ObjInstanceProd] WITH CHECK ADD CONSTRAINT [CK_OLIP] CHECK ([dbo].[fnObjProd]([PID])=0)
--Insert Statement
insert into ObjInstanceProd(OLIID,PID) values (22,51)
Msg 547, Level 16, State 0, Line 1
The INSERT statement conflicted with the CHECK constraint "CK_OLIP". The conflict occurred in database "tmp", table "dbo.ObjInstanceProd", column 'PID'.
The statement has been terminated.
--Execute Function
select [dbo].[fnObjProd] (51)
0
Initially the Table ObjInstanceProd is empty.. So, no matter what value I put in the table, as long as the function in the constraint returns a 0, it should accept it.. But it does not..
The function is correctly returning a 0 (when executed independently), but for some reason, the check constraint returns a 1
When the CHECK constraint fires, the row is already in the table. Therefore, the function is called, and since there is a row returned by the query, the function returns 1, not 0. Try this. Drop the constraint, insert your row successfully, and then run this query:
SELECT OLIID, PID, dbo.fnObjProd([PID]) FROM dbo.ObjInstanceProd;
It should return 1 for every value of PID. Try to add the constraint now. It will fail for the same reason.
Have you considered using a trigger for this? If you use a check constraint, this will turn any multi-row insert or update into a cursor behind the scenes. This can absolutely kill performance and concurrency depending on how you touch your tables. Here is a simple INSTEAD OF INSERT trigger to prevent bad values going in with a single operation, even for a multi-row insert:
CREATE TRIGGER dbo.trObjProd
ON dbo.ObjInstanceProd
INSTEAD OF INSERT AS
BEGIN
SET NOCOUNT ON;
IF NOT EXISTS
(
SELECT 1 FROM inserted
WHERE EXISTS
(
SELECT 1
FROM dbo.ObjInstanceProd AS olip
INNER JOIN dbo.ObjInstance AS oli
ON olip.OLIID = oli.OLIID
INNER JOIN dbo.ObjLevel AS ol
ON ol.OLID = oli.OLID
WHERE
ol.Name in ('Toyota','Lexus')
AND olip.PID = inserted.PID
)
)
BEGIN
INSERT ObjInstanceProd(OLIID, PID)
SELECT OLIID, PID FROM inserted;
END
ELSE
BEGIN
RAISERROR('At least one value was not good.', 11, 1);
SELECT OLIID, PID FROM inserted;
END
END
GO
If you're going to stick with a function, this is a much more efficient approach, however you need to define a way to determine that the current row being inserted is excluded from the check - I couldn't determine how to do that because there are no constraints on dbo.ObjInstanceProd. Is OLIID, PID unique?
ALTER FUNCTION [dbo].[fnObjProd]
(
#Pid INT
)
RETURNS BIT
WITH EXECUTE AS CALLER
AS
BEGIN
RETURN
(
SELECT CASE WHEN EXISTS
(
SELECT 1
FROM dbo.ObjInstanceProd AS olip
INNER JOIN dbo.ObjInstance AS oli
ON olip.OLIID = oli.OLIID
INNER JOIN dbo.ObjLevel AS ol
ON ol.OLID = oli.OLID
WHERE
ol.Name in ('Toyota','Lexus')
AND olip.PID = #Pid
) THEN 1 ELSE 0 END
);
END
GO

Resources