I want to insert values into a table's column and for every value inserted I want to copy all the rows `wHERE anotherColumn ='someString'
Then I want to update the id of the rows inserted based on the name they have (rN
).
Table definition:
myFirstTable
rN rID rnk dateR value1 value2 calculation1 calculation2 calculation3
abc_3m 3 abc_3mxfx 20.10.2010 1 3 4 3 0.33
abc_6m 4 abc_6mxfx 20.10.2010 2 1 3 8 4
First, let's insert new values in rN
. Values taken where rN
= abc_6m
insert into #myFirstTable (rN)
values
('abc_6m'), ('abc_1y'), ('abc_2y'), ('abc_3y'), ('abc_4y'), ('abc_5y'), ('abc_7y'), ('abc_10y'), ('abc_15y'), ('abc_30y')
query 1
update #myFirstTable
set rN = (select * from #myFirstTable
where rN = 'abc_6m')
where rN in (
'abc_6m', 'abc_1y', 'abc_2y', 'abc_3y', 'abc_4y', 'abc_5y', 'abc_7y', 'abc_10y', 'abc_15y', 'abc_30y'
)
The table would become:
#myFirstTable
rN rID rnk dateR value1 value2 calculation1 calculation2 calculation3
abc_3m 3 abc_3mxfx 20.10.2010 1 3 4 3 0.33
abc_6m 4 abc_6mxfx 20.10.2010 2 1 3 8 4
abc_1y 4 abc_6mxfx 20.10.2010 2 1 3 8 4
abc_2y 4 abc_6mxfx 20.10.2010 2 1 3 8 4
and so on, for all the values inserted.
then i want to update the rID
to the correct value so the column rID would look like this:
rN rID rnk dateR value1 value2 calculation1 calculation2 calculation3
abc_3m 3 abc_3mxfx 20.10.2010 1 3 4 3 0.33
abc_6m 4 abc_6mxfx 20.10.2010 2 1 3 8 4
abc_1y 5 abc_6mxfx 20.10.2010 2 1 3 8 4
abc_2y 6 abc_6mxfx 20.10.2010 2 1 3 8 4
In order to do so, I was thinking of writing something like this:
query 2
update #myFirstTable
set rID = (case when rnk = 'abc_1y' then rID = '100',
case when rnk = 'abc_2y' then rID = '101'
case when rnk = 'abc_3y' then rID = '102'
case when rnk = 'abc_4y' then rID = '103'
case when rnk = 'abc_5y' then rID = '104'
case when rnk = 'abc_7y' then rID = '105'
case when rnk = 'abc_10y' then rID = '106'
case when rnk = 'abc_15y' then rID = '107'
case when rnk = 'abc_30y' then rID = '108'
) end
select * from #myFirstTable
where rN = 'abc_6M'
Questions:
1. Is my logic correct for what I'm trying to achieve? (are query1
and query2
ok syntax wise? Can I write something like this in sql server 2012?
2. Is it ok to write an update column = (case when column = then another column = 'value'
like that ?
3. Could I do this in a simpler way somehow using a window function?
ex:
select * from myTable
case (
when rN not in ('abc_1m', 'abc_3m', 'abc_6m') then
select * from #myFirstTable where rN like 'abc_6m'
over (partition by (select * from #myFirstTable where rN like 'abc_6m'))) end
Sorry if I'm not phrasing the question in the most clear way, but I am not sure what I could use and how to use it, that's why I'm looking for some guidence. Thanks