SQL Server 2008 Before Insert Trigger - sql

I have the following Query:
Insert into tblTest (ID, Name, Age) VALUES (1, 'TestName', 20);
In my trigger I want to check - if the query's ID is equal to 1, send another query:
Insert into tblTest (ID, Name, Age) VALUES (2, 'TestName', 21);
Else, dont do anything.
The problem is, I dont know how to keep the parameters as is and just change the age, so basically I want to send the SAME query, and change a certain parameter (in this case, its the age parameter).

The rows about to be inserted can be found in the special inserted table. Here's an example:
if object_id('tblTest') is not null
drop table tblTest
create table tblTest (id int, name varchar(50), age int)
go
create trigger trg_tblTest_BeforeInsert
on tblTest
after insert
as begin
insert tblTest
select id + 1
, name
, age + 1
from inserted
where id = 1 -- Only for rows with id=1
end
go
insert tblTest (id, name, age) values (1, 'TestName', 20)
select * from dbo.tblTest
This prints:
id name age
1 TestName 20
2 TestName 21

Related

PostgreSQL bulk update

In my PostgreSQL database I have the following schema:
CREATE TABLE atc_codes (
id bigint NOT NULL,
name character varying,
atc_code character varying
);
INSERT INTO atc_codes (id, name, atc_code) VALUES (1, 'granisetron', 'A04AA02');
INSERT INTO atc_codes (id, name, atc_code) VALUES (2, '', 'A04AA02');
INSERT INTO atc_codes (id, name, atc_code) VALUES (3, '', 'A04AA02');
INSERT INTO atc_codes (id, name, atc_code) VALUES (4, 'metoclopramide', 'A03FA01');
INSERT INTO atc_codes (id, name, atc_code) VALUES (5, '', 'A03FA01');
INSERT INTO atc_codes (id, name, atc_code) VALUES (6, '', 'A03FA01');
SELECT * FROM atc_codes;
id
name
atc_code
1
granisetron
A04AA02
2
A04AA02
3
A04AA02
4
metoclopramide
A03FA01
5
A03FA01
6
A03FA01
View on DB Fiddle
Now I want to do the following things:
Update all records with act_code equal to A04AA02 to have granisetron value in the name column.
Update all records with act_code equal to A03FA01 to have metoclopramide value in the name column.
In the real database there will be much more scenarios like that so using something like CASE statement is impossible in that case.
Can I do that in one query instead of two?
I found the solution with using view:
WITH act_codes_name AS (
SELECT
name,
atc_code
FROM
atc_codes
WHERE
name IS NOT NULL
)
UPDATE
atc_codes
SET
name = act_codes_name.name
FROM act_codes_name
WHERE act_codes_name.atc_code = atc_codes.atc_code;
Yes you could use a CASE WHEN (standard SQL "switch case") in the SET clause:
UPDATE atc_codes
SET name = CASE
WHEN atc_code = 'A04AA02' THEN 'granisetron'
WHEN atc_code = 'A03FA01' THEN 'metoclopramide'
ELSE name
END
WHERE atc_code IN('A04AA02', 'A03FA01');
To avoid mistakes, I added a ELSE (equivalent to a default case) and a WHERE clause to prevent updating rows that don't match. Both do the same thing and I think you could just use one or the other.

Insert into table from select only when select returns valid rows

I want to insert into table from select statement but it is required that insert only happens when select returns valid rows. If no rows return from select, then no insertion happens.
insert into products (name, type) select 'product_name', type from prototype where id = 1
However, the above sql does insertion even when select returns no rows.
It tries to insert NULL values.
I know the following sql can check if row exists
select exists (select true from prototype where id = 1)
How to write a single SQL to add the above condition to insert to exclude the case ?
You are inserting the wrong way. See the example below, that doesn't insert any row since none matches id = 1:
create table products (
name varchar(10),
type varchar(10)
);
create table prototype (
id int,
name varchar(10),
type varchar(10)
);
insert into prototype (id, name, type) values (5, 'product5', 'type5');
insert into prototype (id, name, type) values (7, 'product7', 'type7');
insert into products (name, type) select name, type from prototype where id = 1
-- no rows were inserted.

INSERT fails with ORA-01400: cannot insert NULL

I am working with ORACLE SQL Developer and I created a table with an id as PK, another FK, id_columnx and a column1 and inserted data into them. Then I added another 2 columns, column 2 and column 3 and when I try to insert data into these new added columns, I get the error:
ORA-01400: cannot insert NULL.
I have to mention that I don't have any triggers on the table and i DO have values in the INSERT statement. There seems to be a conflict with the PK id, but I don't understand why.
So here is the code:
create table mytable(id INT PRIMARY KEY, name varchar2(30));
insert into mytable values (1, 'Mary');
insert into mytable values (2, 'John');
insert into mytable values (3, 'Bill');
alter table mytable
add email VARCHAR2(30);
alter table mytable
add addess VARCHAR2(30);
insert into mytable (email, addess)
values ('mary#gmail.com', 'Street X');
And here is the error I get:
Error starting at line : 12 in command -
insert into mytable (email, addess)
values ('mary#gmail.com', 'Street X')
Error report -
ORA-01400: cannot insert NULL into ("ZAMFIRESCUA_49"."MYTABLE"."ID")
INSERT is for inserting new rows, UPDATE is for altering data in the current rows. As mentioned in the comments, it looks like you want to be updating Mary's row with her email/address:
UPDATE mytable
SET email = 'mary#gmail.com',
address = 'Street X'
WHERE ID = 1 --Mary's ID for example, replace with the ID of the row you want to update
You could also use a subquery to find the right ID so you don't have to always look it up:
UPDATE mytable
SET email = 'mary#gmail.com',
address = 'Street X'
WHERE ID = (SELECT ID FROM mytable WHERE name = 'Mary')
Edit:
I was thinking there were two tables while writing this answer, you could always just use the name field as your filter:
UPDATE mytable
SET email = 'mary#gmail.com',
address = 'Street X'
WHERE name = 'Mary'
You're missing a PK value in your last INSERT after the ALTER statements. Try this:
create table mytable(id INT PRIMARY KEY, name varchar2(30));
insert into mytable values (1, 'Mary');
insert into mytable values (2, 'John');
insert into mytable values (3, 'Bill');
alter table mytable add email VARCHAR2(30);
alter table mytable add addess VARCHAR2(30);
insert into mytable (id, email, addess) values (4, 'mary#gmail.com', 'Street X');

How to insert conditionally in Oracle?

I've read here that the syntax looks like this:
INSERT
WHEN ([Condition]) THEN
INTO [TableName] ([ColumnName])
VALUES ([VALUES])
ELSE
INTO [TableName] ([ColumnName])
VALUES ([VALUES])
SELECT [ColumnName] FROM [TableName];
But I don't want to provide values from another table. I just want to type them, so I've got:
INSERT
WHEN EXISTS (SELECT 1 FROM FOO WHERE NAME = 'JOE')
THEN
INTO BAR (NAME, AGE)
VALUES ('JOE', 50)
and this produces exception: ORA-00928: missing SELECT keyword.
I want to perform an insert if given value is found in another table.
Using with select works. Your query wasn't working because there is a problem with values keyword when inserting conditionally.
INSERT
WHEN EXISTS (SELECT 1 FROM FOO WHERE NAME = 'JOE')
THEN
INTO BAR (NAME, AGE)
SELECT 'JOE', 50 FROM DUAL
So, I've found an indirect way here and solution for my question would be:
INSERT INTO BAR (NAME, AGE)
SELECT 'JOE', 50
FROM DUAL
WHERE EXISTS (SELECT 1 FROM FOO WHERE NAME = 'JOE')
but it doesn't explain why I have to use SELECT statement in INSERT WHEN

SQL Server return wrong result when I use LIKE

I created a new DB "TEST", add a new table "tblTest" and 1 column "Name" in it.
Insert some records: Minh, Tinh, Justin
create database TEST
go
use test
go
create table tblTest (Name varchar(50))
go
insert tblTest values ('Minh')
insert tblTest values ('Tinh')
insert tblTest values ('Justin')
Then I run this query
Select * from tblTest where Name like '%in%'
The result is: Justin. (Minh and Tinh are not display)
Anyone can tell me how to fix this?
Check this example, its give me your result as you want. First % is used for preceed and Last % used for succeeded.
declare #t table (name varchar(50))
insert into #t values('Minh'),('Tinh'),('Justin')
Select * from #t where Name like '%in%'
Result will be
name
Minh
Tinh
Justin
See if this query is working and providing the necessary output.
with tblTest as
(
Select 'Minh' name from dual union
Select 'Tinh' name from dual union
Select 'Justin' name from dual
)
Select * from tblTest where Name like '%in%'
Else, delete all records from tblTest using:
DELETE from tblTest;
Then, insert records using:
INSERT INTO TBLTEST (NAME) VALUES ('Minh');
INSERT INTO TBLTEST (NAME) VALUES ('Tinh');
INSERT INTO TBLTEST (NAME) VALUES ('Justin');
Now try executing your SELECT query again.
As #podiluska pointed out, there could be some foreign junk characters.