loop through numerous "if exists update, else insert" statements? - sql

I have a script that needs to insert 50+ rows into a table, is there a way to loop though each row I want to insert, rather than coding this below statement 50 + times in TSQL?
IFEXISTS ( SELECT 1 FROM table where column 1 = )
UPDATE table
Column1 = value,
Column2 = value,
Column3 = value,
Column4 = value
WHERE column 1 =
ELSE
INSERT INTO table
(Column1, Column2, Column3, Column4)
VALUES
(value, value, value, value)

Even better, you can put the records in a temporary table, then update all that exists and insert all that doesn't exist with two queries.
Example:
select Column1 = 1, Column2 = 2, Column3 = 3
into #temp
union all select 1,2,3
union all select 1,2,3
union all select 1,2,3
...
union all select 1,2,3
update t
set Column1 = p.Column1, Column2 = p.Column2, Column3 = p.Column3
from table t
inner join #temp p on p.Column1 = t.Column1
insert into table (Column1, Column2, Column3)
select p.Column1, p.Column2, p.Column3
from #temp p
left join table t on t.Column1 = p.Column1
where t.Column1 is null
drop table #temp

Consider the MERGE statement (and specifically the first example on the linked page).
This allows you to define operations for add, update or remove when comparing the content of a table and a select query.

Well, SQL is a SET based language so ideally you keep it in a set. To iteratively loop you could use a cursor, but why?
Here is another approach off of an MSDN blog:
UPDATE Table1 SET (...) WHERE Column1='SomeValue'
IF ##ROWCOUNT=0
INSERT INTO Table1 VALUES (...)

Related

Insert columns into new table where one of the columns doesn't allow null values

I am attempting to insert 50 rows at a time from one table into another, however I am unable to bypass the 'Not Null' column in the table I am attempting to INSERT INTO.
Please note I am not able to alter that column so it accepts nulls.
I have 2 tables (table 1 and table 2). I am inserting 2 columns from table 1 into table 2 (table 2 is currently empty). The problem is that table 2 has a third column which cannot have null values.
This is what I have so far.
-- Checking what exists in Table 1 that doesn't exist in Table 2 before inserting
IF EXISTS (SELECT T1.Column1, T1.Column2
FROM Table_1 T1
LEFT JOIN Table_2 T2 on T1.Column1=T2.Column1
WHERE T2.Column1 IS NULL)
BEGIN
INSERT INTO Table_2 (Column1, Column2)
SELECT TOP(50) Column1, Column2
FROM Table_1
ORDER BY Column1
SELECT ##ROWCOUNT
END
IF ##ROWCOUNT < 50
(
SELECT *
FROM Table_2
)
BEGIN
UPDATE Table_2
SET Column3 = 0
END
The problem is that Column 3 in Table 2 does not exist in Table 1 so there is nothing I can insert into Table 2 from Table 1 to populate the column that does not allow nulls in Table 2.
You can select a constant
INSERT INTO Table_2 (Column1, Column2, Column3)
SELECT top(50) Column1, Column2, 0
FROM Table_1
ORDER BY Column1

How to combine multiple columns into one column?

I'm writing a query and want the results in one column
My current results return like this
Column1 Column2 column3
1 A CAT
I want the results to return like this
Column1
1
A
CAT
SELECT Column1 FROM TableName
UNION ALL
SELECT Column2 FROM TableName
UNION ALL
SELECT Column3 FROM TableName
If you don't want duplicate values, use UNION instead of UNION ALL.
You can also do this using UNPIVOT operator
SELECT Column123
FROM
(
SELECT Column1, Column2, Column3
FROM TableName
) AS tmp
UNPIVOT
(
Column123 FOR ColumnAll IN (Column1, Column2, Column3)
) AS unpvt;
https://www.w3schools.com/sql/sql_union.asp
https://www.mssqltips.com/sqlservertip/3000/use-sql-servers-unpivot-operator-to-help-normalize-output/
The answer is.. it depends..
If the number of columns are unknown.. then use unpivot as UZI has suggested
if you know all columns and is a small finite set..
you can simply go
Select
column1
from table
union all
select column2
from table
union all
select column3
from table
The Cartesian product of the T table with derived table of 3 rows.(each row of #t is presented 3 times, for а=1 and а=2 and а=3). For the first case we take value from Column1,
and for the second - from Column2 and for the Third - from Column3.
Here, certainly, there is both union and join but, in my opinion, the title's question means single scanning the table.
CREATE TABLE #t (Column1 NVARCHAR(25),Column2 NVARCHAR(25), column3 NVARCHAR(25))
INSERT INTO #t
SELECT '1','A','CAT'
SELECT
CASE a WHEN 1 THEN Column1 WHEN 2 THEN Column2 ELSE column3 END col
FROM #t, (SELECT 1 a UNION ALL SELECT 2 UNION ALL SELECT 3) B
DROP TABLE #t

select table to select from, dependent on column-value of already given table

for my intention I have to select a table to select columns from dependent on the column-value of an already given table.
First I thought about a CASE construct, if this is possible with sqlite.
SELECT * FROM
CASE IF myTable.column1 = "value1" THEN (SELECT * FROM table1 WHERE ...)
ELSE IF myTable.column1 = "value2" THEN (SELECT * FROM table2 WHERE ...)
END;
I am new to SQL. What construct would be the most concise (not ugly) solution and if I cannot have it in sqlite, what RDBM would be the best fit?
Thanks
Here is a proposal for associating a value from one of two tables for each entry in mytable. I.e. this is making the assumption that mytable does not only contain a single entry for choosing the secondary table.
For details on what this means, see "MCVE" at the end of this answer.
If you want to switch between two secondary tables, based on a single entry in main table, see at the very end of this answer.
Details:
a hardcoded "value1"/"value2" as column1 added on the fly to the result from secondary tables
joining by the faked colummn1 and a secondary join-key, assumption here id
a union all to make a single table from both secondary tables (including the fake column1)
select *
from mytable
left join
(select 'value1' as column1, * from table1
UNION ALL
select 'value2' as column1, * from table2)
using(id, column1);
Output (for the MCVE provided below, "a-f" from table1, "A-Z" from table2):
value1|1|a
value2|2|B
value1|3|c
value1|4|d
value2|5|E
value2|6|F
MCVE:
PRAGMA foreign_keys=OFF;
BEGIN TRANSACTION;
CREATE TABLE mytable (column1 varchar(10), id int);
INSERT INTO mytable VALUES('value1',1);
INSERT INTO mytable VALUES('value2',2);
INSERT INTO mytable VALUES('value1',3);
INSERT INTO mytable VALUES('value1',4);
INSERT INTO mytable VALUES('value2',5);
INSERT INTO mytable VALUES('value2',6);
CREATE TABLE table2 (value varchar(2), id int);
INSERT INTO table2 VALUES('F',6);
INSERT INTO table2 VALUES('E',5);
INSERT INTO table2 VALUES('D',4);
INSERT INTO table2 VALUES('C',3);
INSERT INTO table2 VALUES('B',2);
INSERT INTO table2 VALUES('A',1);
CREATE TABLE table1 (value varchar(2), id int);
INSERT INTO table1 VALUES('a',1);
INSERT INTO table1 VALUES('b',2);
INSERT INTO table1 VALUES('c',3);
INSERT INTO table1 VALUES('d',4);
INSERT INTO table1 VALUES('e',5);
INSERT INTO table1 VALUES('f',6);
COMMIT;
For selecting between two tables based on a single entry in main table (in this case "mytable2":
select * from table1 where (select column1 from mytable2) = 'value1'
union all
select * from table2 where (select column1 from mytable2) = 'value2';
Output (with mytable2 only containing 'value1'):
a|1
b|2
c|3
d|4
e|5
f|6

Select statement for Oracle SQL

I have a table say,
column1 column2
a apple
a ball
a boy
b apple
b eagle
b orange
c bat
c ball
c cork
Now I would like to fetch column1 based on the rows that doesn't contain 'apple' and also ignore values in column1 if any of the rows have 'apple' in it. So in the table above only 'C' must be retured.
I am kind of new to Oracle SQL and I know Select column1 from table where column2 != 'apple' will not work. I need some help with this please.
You could use DISTINCT with NOT IN in following:
QUERY 1 using NOT IN
select distinct col1
from t
where col1 not in (select col1 from t where col2 = 'Apple')
QUERY 2 using NOT EXISTS
As per #jarlh comment you could use NOT EXISTS in following:
select distinct col1
from #t t1
where not exists (select 1 from #t t2 where col2 = 'Apple' and t1.col1 = t2.col1)
SAMPLE DATA
create table t
(
col1 nvarchar(60),
col2 nvarchar(60)
)
insert into t values
('a','apple')
,('a','ball')
,('a','boy')
,('b','apple')
,('b','eagle')
,('b','orange')
,('c','bat')
,('c','ball')
,('c','cork')
Assuming that column1 is NOT NULL you could use:
SELECT DISTINCT t.column1
FROM table_name t
WHERE t.column1 NOT IN (SELECT column1
FROM table_name
WHERE column2 = 'apple');
LiveDemo
To get all columns and rows change DISTINCT t.column1 to *.
Select * from tbl
Left join (
Select column1 from tbl
Where column2 like '%apple%'
Group by column1
) g on tbl.colum1 = g.column1
Where g.column1 is null
Seems to me that you need to find a summary of all colum1 values that have any reference to apple. Then list the rows that have no match to the summary list (g)
If I understand well, you need the values af column1 such that in your table does not exist a row with the same value of column1 and 'apple' in column2; you can translate this in SQL with:
Select column1
from your_table t
where not exists (
select 1
from your_table t2
where t2.column1 = t1.column1
and t2.column2= 'apple'
)
This is only one of the possible ways to get your result, soyou can rewrite it in many ways; I believe this way of writing is similar enough to the logics to clearly explain how a logic could be written in plain SQL.

SQL Count/Sum displaying column as rows

I have a table with 4 bit columns
I need to create a report that will show the total of all "true" values for each column but I need the column names to return as a row.
For examples, the table will contain:
Column1 Column2 Column3
1 1 0
0 1 0
1 1 0
The result should be:
Category Value
Column1 2
Column2 3
Column3 0
The table has other columns, I just need specific ones
Thanks
I don't know if there are other approaches, but the following should work:
select 'Column1' as "Category", sum(column1) as "Value" from my_table union
select 'Column2', sum(column2) from my_table union
select 'Column3', sum(column3) from my_table
Here's a SQLFiddle for it.
You can try UNPIVOT on the table (this is for SQL Server)
create table Test (Column1 bit, Column2 bit, Column3 bit)
insert into Test values (1,1,0)
insert into Test values (0,1,0)
insert into Test values (1,1,0)
SELECT Value, sum(Vals)
FROM
(CONVERT(INT, Column1) Column1, CONVERT(INT, Column2) Column2, CONVERT(INT, Column3) Column3
FROM Test) p
UNPIVOT
(Vals FOR Value IN
(Column1, Column2, Column3)
)AS unpvt
GROUP BY Value
PIVOT/UNPIVOT documentation
http://sqlfiddle.com/#!6/957c6/1/0
Try this:
select
category = "column1", value = sum (convert(int,col1)) from MyTable1
union
select
category = "column2", value = sum (convert(int,col2)) from MyTable1
union
select
category = "column3", value = sum (convert(int,col3)) from MyTable1