how to use case to do multiple insert in a table in postgres - sql

I am using a case like this in stored procedure.
BEGIN
FOREACH abc IN array abcarray
LOOP
case abc
when abc1 then INSERT 1 into table a;
when abc2 then INSERT 2 into table a;
else
--do nothing
end case;
END LOOP;
Is this the proper way to use case if the requirement is to insert both 1 and 2 in the table or should i try something else?

You don't need a loop or PL/pgSQL for that. You can embed a CASE expression into a SELECT that acts as the source for the INSERT
insert into table_a (some_column)
select case
when abc = 'abc1' then 1
when abc = 'abc2' then 2
end
from unnest(abcarray) as x(abc);

Related

Looping over HANA table

I'm trying to create a stored procedure in HANA that should loop through a table. Lets say I have 3 columns, ColumnA, ColumnB and ColumnC. In ColumnA, I have my identifiers that I would like to loop over. In ColumnB, I have related identifiers, but in some cases, the identifiers in ColumnB, can be the same as whats in ColumnA. In ColumnC I have a COUNT.
So the table looks like:
ColumnA | ColumnB | ColumnC
0001 | 0002 | 0
0003 | 0004 | 0
0002 | 0005 | 6
The process should loop over each row and check ColumnC to see if the value in ColumnC is greater than 0. If its not, then take the related identifier from ColumnB, and look for it in ColumnA. If there is a value there greater than 0, the loop should insert that line into a table and break.
Any suggestion would be useful, I'm also open to using different methods, besides a procedure.
BEGIN
DECLARE V_NO INT;
DECLARE LV_LOOP INT;
SELECT count(*) INTO V_NO FROM "YOURTABLE";
FOR LV_LOOP IN 1..:V_NO DO
SELECT "COLUMNC" INTO LV_COLUMNC FROM "YOURTABLE";
IF :LV_COLUMNC > 0 THEN
INSERT INTO "YOURTABLE1" VALUES (.....);
ELSE
SELECT "COLUMNB" INTO LV_COLUMNB FROM "YOURTABLE";
SELECT "COLUMNA" INTO LV_COLUMNA FROM "YOURTABLE";
IF :LV_COLUMNB = :LV_COLUMNA THEN
SELECT 'PASS' FROM DUMMY;
END IF;
END IF;
END FOR;
END;
Please let me know if it resolved your issue.

Loop through rows of a query in T-SQL?

I have the following T-SQL script:
declare #Name nvarchar
declare data cursor for
select Name from MyDB.dbo.MyTable;
OPEN data;
-- Perform the first fetch.
FETCH NEXT FROM data;
-- Check ##FETCH_STATUS to see if there are any more rows to fetch.
WHILE ##FETCH_STATUS = 0
BEGIN
-- This is executed as long as the previous fetch succeeds.
FETCH NEXT FROM data INTO #Name;
Print 'Name: ' + #Name
END
CLOSE data;
DEALLOCATE data;
GO
I want to make a script that will compare each of the strings in a first column with each of the strings in the second column.
The problem is, I don't know how to loop through each of the rows and take a separate string value.
The code above prints only the first value in the query result.
What am I doing wrong?
To compare all values from one column to all values in another column you don't need a cursor, a simple join will do the work - since you didn't provide sample data and also not desired results, I had to make my own:
Create and populate sample table (Please save us this step in your future questions)
CREATE TABLE MyTable
(
Id int identity(1,1),
Name1 char(3),
Name2 char(3)
)
INSERT INTO MyTable (Name1, Name2) VALUES
('abc','def'),('zyx','abc'),
('ghi','jkl'),('yza','ghi'),
('mno','pqr'),('nml','mno'),('pqr','qpo'),
('stu','vwx'),('wvu','tsr'),('kji','hgf')
The query:
SELECT T1.Id, T1.Name1, T1.Name2, T2.Id, T2.Name1, T2.Name2
FROM MyTable T1
JOIN MyTable T2 ON T1.Name1 = T2.Name2
Result:
Id Name1 Name2 Id Name1 Name2
1 abc def 2 zyx abc
3 ghi jkl 4 yza ghi
5 mno pqr 6 nml mno
7 pqr qpo 5 mno pqr
You probably don't want to use a Cursor.
Are your columns in the same table? If so this is as simple as this;
-- Show All rows with [DIFFERENT] Name and Name2 fields
SELECT
Name,
Name2
FROM [MyDB].[dbo].[MyTable]
WHERE
Name <> Name2
-- Show All rows with [SAME] Name and Name2 fields
SELECT
Name,
Name2
FROM [MyDB].[dbo].[MyTable]
WHERE
Name = Name2
If not you will need to post the table definitions and names of columns to get a more concrete example

If Else Statement to Skip Value if populated

I am trying to create an if else script to skip a record if there is a specific value in a column of the table and continue to insert records into a different table.
How do I create the script to perform this action?
IF EXISTS (Select * From Table A where X =1)
BEGIN
Do nothing
END
ELSE
BEGIN
INSERT INTO TABLE Y
SELECT * FROM TABLE Z
END
Instead, write a single statement:
INSERT INTO TABLE Y
SELECT *
FROM TABLE Z
WHERE NOT EXISTS (Select 1 From Table A where X = 1);
The conditional is not needed at all.
If you want it in a proc to execute, use it this way
create procedure usp_insert
as
BEGIN
declare #rowcount int = (Select count(*) From TableA where X <>'1')
Begin
if #rowcount>=1
INSERT INTO TABLE Y
SELECT * FROM TABLE Z
end
END

SQL Server execute stored procedure in update statement

every updated record must have different value by using a procedure
the procedure returns single integer value
declare #value int;
exec #value = get_proc param;
update table1 set field1 = #value;
this will work for one record but i want the procedure to get new value for each record
Just a quick example of how to use a TVF to perform this type of update:
USE tempdb;
GO
CREATE TABLE dbo.Table1(ID INT, Column1 INT);
INSERT dbo.Table1(ID)
SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3;
GO
CREATE FUNCTION dbo.CalculateNewValue
(#ID INT)
RETURNS TABLE
AS
-- no idea what this logic would be,
-- just showing an example
RETURN(SELECT NewValue = #ID + 1);
GO
SELECT t1.ID, n.NewValue
FROM dbo.Table1 AS t1
CROSS APPLY dbo.CalculateNewValue(t1.ID) AS n;
Results:
ID NewValue
-- --------
1 2
2 3
3 4
Now an update that uses the same information:
UPDATE t1 SET Column1 = n.NewValue
FROM dbo.Table1 AS t1
CROSS APPLY dbo.CalculateNewValue(t1.ID) AS n;
SELECT ID, Column1 FROM dbo.Table1;
Results:
ID Column1
-- -------
1 2
2 3
3 4
Does it really need to be a procedure ? If you can implement get_proc as function, then you can apply it on every record that you want ;)
Also, what are you using value1 for ? In the example that you've provided, it's not needed.

Build check query

I'm trying to solve this issue with only one select. It can be easily solved with 2, but I want only one:
Imagine this simple table:
create table CheckTest(
name varchar(50)
)
I want a query that fail (it will be inside an if statement) if there isn't any rows on the table or there is a row with name='test'
So, these are the possible scenarios:
--scenario 1 - no rows: should fail
truncate table CheckTest
--scenario2 - rows with value different than "test": should succeed
insert into CheckTest values ('OK')
insert into CheckTest values ('OK')
--scenario3 - 1 row with value "test" or 1 row with value "test" among other rows with value OK
insert into CheckTest values ('test')
insert into CheckTest values ('OK')
insert into CheckTest values ('OK')
I'm planning on using the check like this:
if (<check>)
print 'fail'
else
print 'continue'
It is possible like this:
if (select count(c1.name) + case when count(*) = 0 then 1 else 0 end
from #CheckTest c
left join #CheckTest c1 on c.name = c1.name and c1.name = 'test' ) > 0
begin
select 'fail'
end
else
begin
select 'success'
end
It is possible but I wouldn't bother.
All the ways I can think of that combine this into one SELECT (e.g. using COUNT or DENSE_RANK) are less efficient than two separate queries. One way below.
IF NOT EXISTS(SELECT *
FROM CheckTest
HAVING SUM(DISTINCT CASE
WHEN name = 'test' THEN 1
ELSE 2
END) = 2)
PRINT 'fail'
ELSE
PRINT 'continue'