How to loop through one table and then Insert into another based on multiple IF ELSE - sql

I have a table like below with 2 columns. This table already is populated with all the data I need.
Table 1
ID (int) TYPE (string)
The other table looks like this and it's empty
Table 2
ID (int) Somedetail (int)
I need to loop through Table 1 and then insert into Table 2 if TYPE = 'string'
for each row and I have about 5 different string I need to test against.
INSERT WILL BE insert into Table 2 (ID, int). I will provide the int value based on if TYPE = 'string' matches or not.
This is what I have currently.
SELECT ID, TYPE
FROM TABLE1
IF(ID = 'STRING1')
INSERT INTO TABLE2...
ELSE IF (ID = 'STRING2')
INSERT INTO
and so on

You are basically looking for an INSERT INTO SELECT statement (https://learn.microsoft.com/en-us/sql/t-sql/statements/insert-transact-sql). In your case this would take the form:
INSERT INTO Table2
SELECT
id,
CASE
WHEN type = 'string1' THEN intvalue1
WHEN type = 'string2' THEN intvalue2
WHEN type = 'string3' THEN intvalue3
WHEN type = 'string4' THEN intvalue4
WHEN type = 'string5' THEN intvalue5
END
FROM Table1
WHERE type IN ('string1', 'string2', 'string3', 'string4', 'string5');
Where we just take the results of that SELECT statement and shove it into Table2 with the INSERT INTO.

Fairly positive you want to use CASE based on your comments. You'll have to fill in the strings and the ints that you want, but here is the shell:
INSERT INTO Table2 (ID, Somedetail)
SELECT ID,
CASE WHEN Type = 'string1' THEN 1,
WHEN Type = 'string2' THEN 2,
etc...
END as Somedetail
FROM Table1

Related

SQL Update all rows for one column with a list of values

How can I set all rows of a column by manually typing the values?
My table has 3 rows, I want the column named mycolumn to have 3 values a, b and c (currently those values are NULL):
update mytable set mycolumn = ('a','b','c')
ORA-00907 missing right parenthesis
EDIT: my table is very simple, I have one column ID INT NOT NULL with values 1, 2, 3 and another column mycolumn with all NULL values and I want those values to become 'a' where ID = 1, 'b' where ID=2 etc.
EDIT2: I might have a huge amount of rows, so I want to avoid typing every single ID value where to replace mycolumn. Isn't it possible to match the ID values of 1 to 3 to the values 'a', 'b', 'c' in an automatic way, something like match(ID, ('a','b','c')) perhaps
I just want to replace all values of mycolumn by increasing order of ID. ID being strictly equivalent to what I call a row number in a matrix
EDIT3: I'd like a solution which would work in a general case with all sorts of values, not only the letters of the alphabet given here for simplicity. What if for example my values to replace in mycolumn are ('oefaihfoiashfe', 'fiaohoawdihoiwahopah', 'aefohdfaohdao')? However the ID row numbers will always be a sequence from 1 to N by 1.
Obviously, you should do this in a single update. Like this:
update mytable
set mycolumn = case id when 1 then 'a' when 2 then 'b' when 3 then 'c' end
;
More compact (but also more cryptic, and only works in Oracle, while case expressions are in the SQL standard):
update mytable
set mycolumn = decode(id, 1, 'a', 2, 'b', 3, 'c')
;
Note - this only works if there really are only three rows. If you have many more rows, make sure to add where id in (1, 2, 3) at the end. Otherwise all the OTHER values (in the other rows) will be updated to null!
You can try an update like the one below. This will update 1 > a, 2 > b, 3 > c, 4 > d, etc. When you reach ID 27, since there are no more letters, it will begin at a again and continue down the alphabet.
UPDATE mytable
SET mycolumn = CASE MOD (id, 26)
WHEN 0 THEN 'z'
ELSE CHR (MOD (id, 26) + 96)
END;
Update
To update based on any list of values, you can try an update statement like the one below. If you add a 4th item to the comma delimited list, ID 4 in mytable will be set to whatever you specified as the 4th value.
UPDATE mytable
SET mycolumn =
(SELECT COLUMN_VALUE
FROM (SELECT ROWNUM AS row_num, t.COLUMN_VALUE
FROM TABLE (
sys.odcivarchar2list ('oefaihfoiashfe',
'fiaohoawdihoiwahopah',
'aefohdfaohdao')) t)
WHERE row_num = id);
Hmmm . . . A row can only have one value. Perhaps something like this to assign random values:
update mytable
set mycolumn = (case floor(dbms_random.random * 3)
case 0 then 'a' case 1 then 'b' else 'c'
end)
if you want the 3 rows to have different values a, b and c then you will have to write 3 update statements.
update mytable set mycolumn = 'a' where id = 1;
update mytable set mycolumn = 'b' where id = 2;
update mytable set mycolumn = 'c' where id = 3;

Rename category in the column in SQL Server

Here is the query
select col1
from table
col1 contains these category values:
A
B
C
NULL
How can I rename null category to D?
If you want to make the change permanent
UPDATE table
SET col1 = 'D'
WHERE col1 IS NULL
From then on you can simply query with ...
SELECT col1
FROM table
... to get the desired result.
If there is more than one row having a NULL in col1, you need to filter by a unique key, preferably by the primary key (which every table should have by the way). Let's say you have a table like
id (PK) col1
--- ----
1 'A'
2 'B'
3 'C'
4 NULL
5 NULL
then you can fix it with
UPDATE table SET col1 = 'D' WHERE id = 4;
UPDATE table SET col1 = 'E' WHERE id = 5;
unless you can calculate the new value from another column, e.g.:
UPDATE table
SET col1 = UPPER(LEFT(name, 1))
Try this : ISNULL( ) function is used to replace NULL value with another value
select isnull(col1,'D') as col1
from table
SQL Server uses ISNULL().
SELECT ISNULL(value_to_check, use_this_instead_if_valuetocheck_is_null)
For your code:
select ISNULL(col1, 'D') AS col_name
from table
However, this will happen across the board for this column. You can't use this to make a sequence, like D then E then F. Any NULL value you come across in this column will change to D.

return the column name from dynamic string

I want to get the column from the dynamic string, In my table: MyTable2 I have many columns/fields, which are :
MyVarCharColumnName1,MyVarCharColumnName2,MyVarCharColumnName3,MyVarCharColumnName4
These above fields are nvarchar(50),
I wonder how I can get the value of them when join with another table as below example:
SELECT
*,
CASE
WHEN Tbl1.MyId IN ('1', '2', '3', '4')
THEN (SELECT 'MyVarCharColumnName' + bf.MyId
FROM MyTable2)
ELSE Tbl1.MyId
END AS TheNameofId
FROM
Tbl1
above is wrong because it will return MyVarCharColumnName1 as TheNameofId value instead of the value inside MyVarCharColumnName1
Is there are some sql function that can return the column name from a string?
any way to convert 'MyVarCharColumnName1' to column object?
As it is confirmed that you have to write dynamic query to do in the same way as you are asking but beside that we can do the same in the following way using CASE
SELECT
*,
CASE
WHEN Tbl1.MyId = 1 THEN MyVarCharColumnName1
WHEN Tbl1.MyId = 2 THEN MyVarCharColumnName2
WHEN Tbl1.MyId = 3 THEN MyVarCharColumnName3
WHEN Tbl1.MyId = 4 THEN MyVarCharColumnName4
ELSE Tbl1.MyId
END AS TheNameofId
FROM Tbl1

IF ELSE in SQL Server

I have the following column in Microsoft SQL Server called Type and I want to create another column called Type 1 which would be 1 if account starts with letter A, 2 if account starts with D....
I am new with this so could someone please advise?
Type Type 1
AD 1
AV 1
AC 1
DE 2
DR 2
DG 2
KL 3
KL 3
Use CASE instead of IF:
SELECT
Type,
CASE
WHEN Type LIKE 'A%' then 1
WHEN Type Like 'D%' THEN 2
WHEN ...
END AS Type1
...
SELECT Type,
CASE WHEN SUBSTRING(Type, 1, 1)='A' THEN 1
WHEN SUBSTRING(Type, 1, 1)='D' THEN 2
WHEN SUBSTRING(Type, 1, 1)='K' THEN 3
ELSE 0 END as 'Type 1'
FROM TableName
As others have pointed out, a CASE statement will meet this need easily.
If you are going to be doing this translation often, consider adding a computed column to the table like so:
if object_id('ComputedColumnTest') is not null
drop table ComputedColumnTest;
go
create table ComputedColumnTest
(
TYPE varchar(2)
);
alter table ComputedColumnTest --<<<<<<<
add TYPE1 AS --<<<<<<<
( --<<<<<<<
case when [TYPE] like 'A%' then 1--<<<<<<<
when [TYPE] like 'D%' then 2--<<<<<<<
else 0 --<<<<<<<
end --<<<<<<<
) --<<<<<<<
insert into ComputedColumnTest([type]) values ('AD')
insert into ComputedColumnTest([type]) values ('AV')
insert into ComputedColumnTest([type]) values ('AC')
insert into ComputedColumnTest([type]) values ('DE')
insert into ComputedColumnTest([type]) values ('DR')
insert into ComputedColumnTest([type]) values ('DG')
insert into ComputedColumnTest([type]) values ('KL')
insert into ComputedColumnTest([type]) values ('KL')
select *
from ComputedColumnTest
where type1 = 2
If you want to put WHERE on computed column, you have to wrap it in subquery.
SELECT *
FROM (
SELECT Type
, (CASE LEFT(Type, 1)
WHEN 'A' THEN 1
WHEN 'D' THEN 2
END) AS Type1
) a
WHERE Type1 = 'some condition'
I know this question has been answered already but I thought I would add my 2 cents.
If the amount of possible values is going to get very large, causing the case statement to become very large you may want to consider creating a loopkup table for yourself.
You would the be able to just do a join between the 2 tables to get the relevant column value.
If you wanted to number using the first letter of the 'type' column in ascending order, use the DENSE_RANK() in SQL Server.
;WITH cte_1
AS
( SELECT Type
,DENSE_RANK() OVER (ORDER BY LEFT(Type,1) ) [Type 1]
FROM YourTable)
SELECT *
FROM cte_1
WHERE [Type 1]=1 --here you can add your filter criteria

insert select alias value into column

Not sure if this is the best title, but i want to select string values into an int column of a new table (the reason is to use keys with int data types rather than strings, so there are more columns not shown in this example)
table1.key1 table2.key2
a 1
b 2
c 3
a 1
one way i can do this is as follows but the syntax is very very long in some scenarios
insert into table2 (key2)
select 1
from table1
where key1 = 'a'
insert into table2 (key2)
select 2
from table1
where key1 ='b'
etc...
can someone show me how i could use a syntax that is shorter? also i have to keep identity insert set to off so an update statement will not work from what i understand.
SQL Fiddle Demo
Use a CASE expresion
insert into table2 (key2)
select CASE WHEN key1 = 'a' THEN 1
WHEN key1 = 'b' THEN 2
WHEN key1 = 'c' THEN 3
.....
ELSE -1
END as key2
from table1