A.Salehi
A.Salehi

Reputation: 33

Iterate through a list using SQL While Loop

I have written a SQL query that joins two tables and calculates the difference between two variables. I want a while loop iterate through the code and do the procedure for a list of organizations numbers orgnr.

Use Intra;
drop table #Tabell1 
go


select Månad = A.Manad, Intrastat = A.varde, Moms = B.vardeutf
into #Tabell1 
From
IntrastatFsum A
join
Momsuppg B
    on A.Orgnr = B.Orgnr
where A.Orgnr = 165564845492
AND A.Ar = 2017
AND B.Ar = A.AR
--AND A.Manad = 11
AND A.Manad = B.Manad
AND A.InfUtf = 'U'
order by A.Manad

select *, Differens = (Intrastat - Moms)/ Moms from #Tabell1 

Where do I put the while loop and how should I write it? I don't have a lot of experience with SQL so any help is appreciated.

wasnt clear at all when posting this question was in a big hurry, so sorry guys for that. But what im trying to do is: This code just runs trough some data, calculates the difference in % for a special company. Each month we get a list of companies that show high standard deviation for some variables. So we have to go through them and compare the reported value with the taxreturn. What im trying to do is write a code that compares the values for "Intra" which is the reported value and " Moms" which is reported tax value. That part i have already done what i need to do now is to insert a loop into the code that goes through a list instead where i have stored the orgnr for companies that show high std for some variables.I want it to keep a list of the companies where the difference between the reported values and taxreturn is high, so i can take an extra look at them. Because sometimes the taxreturn and reported value to ous is almost the same, so i try to remove the most obvious cases with automation

Upvotes: 0

Views: 607

Answers (3)

paparazzo
paparazzo

Reputation: 45106

Question is not clear (to me)

select Månad = A.Manad, Intrastat = A.varde, Moms = B.vardeutf 
     , Differens = (A.varde - B.vardeutf) / B.vardeutf
From
IntrastatFsum A
join
Momsuppg B
    on A.Orgnr = B.Orgnr
   AND A.Orgnr in (165564845492, ...)
   AND A.Ar = 2017
   AND A.Manad = B.Manad
   AND A.InfUtf = 'U'
order by A.Manad

Upvotes: 0

Ravi
Ravi

Reputation: 1172

just remove A.Orgnr = 165564845492 in where clause, there is no need of loop

Use Intra;
drop table #Tabell1 
go


select Månad = A.Manad, Intrastat = A.varde,Moms = B.vardeutf
into #Tabell1 
From
IntrastatFsum A
join
Momsuppg B
    on A.Orgnr = B.Orgnr
where  A.Ar = 2017
AND B.Ar = A.AR
--AND A.Manad = 11
AND A.Manad = B.Manad
AND A.InfUtf = 'U'
order by A.Manad

select *, Differens = (Intrastat - Moms)/ Moms from #Tabell1 

Upvotes: 0

Milnev
Milnev

Reputation: 105

I don't think you need a loop in your query.

Try changing this where-clause:

where A.Orgnr = 165564845492

To this:

where A.Orgnr in (165564845492, 123, 456, 678)

Upvotes: 2

Related Questions