How to do one where BEFORE multiple inserts in SQL Server - sql

I'm doing a multiple insert in SQL Server using UNION ALL between the inserts. In the last part of the query I have a WHERE clause. Now it seems that that the WHERE clause is executed before every statement, but I only want the WHERE to be executed one time. If the WHERE clause has a result then none of the inserts should be executed.
For illustration, insert some persons into a table, if any records exists with one of the defined ages none of the inserts should be executed.
INSERT INTO mytable
select 1, 33,john UNION ALL
select 2, 28,james UNION ALL
select 3, 20,Harry UNION ALL
WHERE NOT EXISTS (SELECT 1 FROM mytable where age in(22,28,30))
How should I do this?

Try this instead:
INSERT INTO mytable
(id, age, name)
SELECT * FROM
(
SELECT 1 AS id, 33 AS age, 'john' AS name
UNION ALL
SELECT 2, 28, 'james'
UNION ALL
SELECT 3, 20, 'Harry'
) T1
WHERE NOT EXISTS (SELECT 1 FROM mytable WHERE age IN (22, 28, 30))

Related

How to select a record which have all id's in SQL?

I want select record which have all id's.
Example:
Name
ID
Ram
3
Ajay
1
Mogan
3
Ram
1
Ram
2
Here Ram have all id's (1,2,3). So, I want result as Ram.
WITH CTE(NAME,CODE)AS
(
SELECT 'RAM',1 UNION ALL
SELECT'AJAY',3 UNION ALL
SELECT 'MOGAN',2 UNION ALL
SELECT 'KUMAR',3 UNION ALL
SELECT 'RAM',2 UNION ALL
SELECT 'JAYA',1 UNION ALL
SELECT 'KABIL',3 UNION ALL
SELECT 'RAM',3
)
SELECT C.NAME
FROM CTE AS C
GROUP BY C.NAME
HAVING COUNT(DISTINCT C.CODE)=(SELECT COUNT(DISTINCT CODE) FROM CTE )
As far as I know, this is called "relational division". You can try my query or look for another possible solution
Select * from table where upper(name) = 'RAM'
This query would bring back all the IDs for RAM alone
how about string agg.
CREATE TABLE MyTable (
ID int,
Name varchar(255),
);
Insert into MyTable(ID, Name) values (1, 'Ram');
Insert into MyTable(ID, Name) values (2, 'Ram');
Insert into MyTable(ID, Name) values (3, 'Ram');
Insert into MyTable(ID, Name) values (1, 'Ajay');
Insert into MyTable(ID, Name) values (1, 'Mogan');
select Name, string_agg(ID, ',') as Ids
from MyTable
group by Name;
result
Ajay 1
Mogan 1
Ram 1,2,3
see result here
http://sqlfiddle.com/#!18/923bf/4
With reference to the with clause used by #surgey above,
WITH CTE(NAME,CODE)AS
(
SELECT 'RAM',1 from dual UNION ALL
SELECT'AJAY',3 from dual UNION ALL
SELECT 'MOGAN',2 from dual UNION ALL
SELECT 'KUMAR',3 from dual UNION ALL
SELECT 'RAM',2 from dual UNION ALL
SELECT 'JAYA',1 from dual UNION ALL
SELECT 'KABIL',3 from dual UNION ALL
SELECT 'RAM',3 from dual
)
select name, code, rank() over(partition by name order by code) rank
from cte
this query, it will bring back everybody in the and group them by name. THis could be one possible solution other use tou can use an "IN" clause in your where as shown below
Select * from table where upper(name) in ('RAM','AJAY')
If are you using MySql this will solve your issue:
SELECT r1.name
FROM raws r1
LEFT JOIN raws r2 ON r1.id = r2.id AND r1.name = r2.name
WHERE r2.id IN (1, 2, 3)
GROUP by r1.name
HAVING count(r2.id) = 3; # count of numbers in IN (1, 2, 3)
And if you have identifier in your table use it for join instead
of r1.id = r2.id AND r1.name = r2.name

Insert Into command just works for one Value not for more values because of comma placement

Tried to fill in a table with insert into command, but it just works for one value not for more.
I work with MS Access and the mistake is the comma placement, but I didn't find the mistake. Tried it with just one value and that works, but I have to insert it all.
INSERT INTO Abteilung (ID, Abteilung, Mitarbeiteranzahl)
VALUES (('1', 'Einkauf', '5'), ('2', 'HR', '5'), ('3', 'Controlling', '5'),
('4', 'Produktion', '20'), ('5', 'Vertrieb', '20'),
('6', 'Qualitätsmanagement', '3'), ('7', 'Industrial Engineering', '8')
)
You can't do this as easily in access as other major db but it can be made possible. First off, create yourself a table with one row:
CREATE TABLE dual([Dummy] Integer)
INSERT INTO dual VALUES(1)
Now you can select a bunch of hard coded values "from" this table:
INSERT INTO Abteilung
(
ID,
Abteilung,
Mitarbeiteranzahl
)
SELECT '1' as e1,'Einkauf' as e2, '5' as e3 FROM dual
UNION
SELECT '2','HR','5' FROM dual
UNION
SELECT '3','Controlling','5' FROM dual
UNION
SELECT '4','Produktion','20' FROM dual
UNION
SELECT '5','Vertrieb','20' FROM dual
UNION
SELECT '6','Qulaitätsmanagement','3' FROM dual
UNION
SELECT '7','Industrial Engineering','8' FROM dual
You might need to wrap all those selects in another SELECT * FROM, I can't quite remember
By the time you're done writing all those out you might well get to thinking it would be as easy to just write N number of insert statements..
There is a way how you can insert rows without building SQL strings.
check this Answer
You can't insert more than 1 row with an INSERT statement in Access.
Even multiple INSERT statements separated with ; are not allowed.
You can use a trick though like this:
INSERT INTO Abteilung ( ID, Abteilung, Mitarbeiteranzahl)
SELECT * FROM (
SELECT '1' AS ID, 'Einkauf' AS Abteilung, '5' AS Mitarbeiteranzahl FROM (SELECT COUNT(*) FROM Abteilung)
UNION ALL
SELECT '2','HR','5' FROM (SELECT COUNT(*) FROM Abteilung)
UNION ALL
SELECT '3','Controlling','5' FROM (SELECT COUNT(*) FROM Abteilung)
UNION ALL
SELECT '4','Produktion','20' FROM (SELECT COUNT(*) FROM Abteilung)
UNION ALL
SELECT '5','Vertrieb','20' FROM (SELECT COUNT(*) FROM Abteilung)
UNION ALL
SELECT '6','Qulaitätsmanagement','3' FROM (SELECT COUNT(*) FROM Abteilung)
UNION ALL
SELECT '7','Industrial Engineering','8' FROM (SELECT COUNT(*) FROM Abteilung)
)
Unfortunately the FROM clause is needed for each of the INSERTs and it must return only 1 row, this is why I used SELECT COUNT(*) which for a large table may be not that efficient.
Can you try the following query:
INSERT INTO Abteilung
(
ID,
Abteilung,
Mitarbeiteranzahl
)
SELECT '1','Einkauf','5'
UNION ALL SELECT '2','HR','5'
UNION ALL SELECT '3','Controlling','5'
UNION ALL SELECT '4','Produktion','20'
UNION ALL SELECT '5','Vertrieb','20'
UNION ALL SELECT '6','Qulaitätsmanagement','3'
UNION ALL SELECT '7','Industrial Engineering','8'
Hope this should work.

How to insert multiple insert sql statement

There is a table Person(id, name). I am inserting more than 1000 records into person table. Both id and name should be unique. I wrote something like this
INSERT ALL
INTO PERSON (1, 'MAYUR')
INTO PERSON (2, 'SALUNKE')
.....(1000 records)
SELECT * FROM DUAL;
I am getting unique constraint for name in this query. How do I know which record in particular is failing. All I see in logs is this
Error starting at line : 3 in command - ORA-00001: unique constraint
(UN_PERSON_NAME) violated.
This does not tell the exact record which is duplicate.
You are missing values keyword. Try this!
INSERT ALL
INTO PERSON values(1, 'MAYUR')
INTO PERSON values(2, 'SALUNKE')
.....(1000 records)
SELECT * FROM DUAL;
INSERT INTO table2 (column1, column2, column3, ...)
SELECT column1, column2, column3, ...
FROM table1
Unfortunately, Oracle doesn't support multiple inserts using a single VALUES() statement. I usually approach this as:
INSERT PERSON (id, name)
SELECT 1, 'MAYUR' FROM DUAL UNION ALL
SELECT 2, 'SALUNKE' FROM DUAL UNION ALL
.....;
One advantage of this approach is you can use a subquery and assign the id:
INSERT PERSON (id, name)
SELECT rownum, x.name
FROM (SELECT 'MAYUR' FROM DUAL UNION ALL
SELECT 'SALUNKE' FROM DUAL UNION ALL
.....
) x

Condition before insert SQL

In DB2 SQL, I want to write something like
insert into employees
(id, name) values (1, "emp1")
where (select count(*) from employee_registry) <= 10
Can't figure out the correct syntax though.
post edit.
i wanted to insert records only if some condition is met.
You need to have a SELECT statement somewhere in order to use the WHERE clause, so something like this might work:
insert into employees (id, name)
select 1, 'emp1' from sysibm.sysdummy1
where (select count(*) from employee_registry) <= 10
sysibm.sysdummy1 is a special system table that always has only one row.
Other method, group by Nothing + having :
insert into employees (id, name)
select '1', 'emp1' from employee_registry
group by 1 having count(*)<=10

SELECT ALL with SUM(Col)

Is there a way to Select all and also get the sum of a column all in the same query?
SELECT *, SUM(Colname) FROM `Table`...
Thank you.
This can easily be done using a window function:
select t.*,
sum(some_value) over () as total_sum
from some_table as t;
This is standard SQL and works on all modern DBMS.
SQLFiddle: http://sqlfiddle.com/#!15/c1a74/1
No, if you want to use aggregate functions then you have to GROUP BY and end up getting a single row for the columns you have specified in that GROUP BY col1, col2, col3.
If you want multiple records (SELECT *) and also want the SUM(Colname) of one of them then do it in 2 separate queries.
Yes you can do that with a subquery
SELECT
*
FROM
Table,
(SELECT
SUM(Colname) SumColumn
FROM
Table) t1
I tested in SQL Server with this small example
CREATE TABLE #Test (IntData INT, Data NVARCHAR(20))
INSERT INTO #Test(IntData, Data)
SELECT 1, 'Data1' UNION
SELECT 3, 'Data2' UNION
SELECT 5, 'Data3' UNION
SELECT 7, 'Data4' UNION
SELECT 9, 'Data5' UNION
SELECT 11, 'Data6'
SELECT
*
FROM
#Test,
(SELECT
SUM(IntData) SumIntData
FROM
#Test) t1
DROP TABLE #Test
Hope this helps