I have a quite large script which is shrunk and simplified in this question.The overall principal is that I have some code that need to be run several times with only small adjustments for every iteration. The script is built with a major loop that has several subloops in it. Today the whole select-statement is hard coded in the loops. My thought was that I could write the select-statement once and only let the parts that needs to be changed for every loop be the only thing that changes in the loop. The purpose is easier maintaining.
Example of the script:
declare
@i1 int,
@i2 int,
@t nvarchar(50),
@v nvarchar(50),
@s nvarchar(max)
set @i1 = 1
while @i1 < 3
begin
if @i1 = 1
begin
set @i2 = 1
set @t = 'Ansokningsomgang'
set @s = '
select ' + @v + '_Ar,count(*) as N
from (
select left(' + @v + ',4) as ' + @v + '_Ar
from Vinnova_' + @t + '
) a
group by ' + @v + '_Ar
order by ' + @v + '_Ar
'
while @i2 < 4
begin
if @i2 = 1
begin
set @v = 'diarienummer'
exec sp_executesql
@stmt = @s,
@params = N'@tab as nvarchar(50), @var as nvarchar(50)',
@tab = @t, @var = @v
end
else if @i2 = 2
begin
set @v = 'utlysning_diarienummer'
exec sp_executesql
@stmt = @s,
@params = N'@tab as nvarchar(50), @var as nvarchar(50)',
@tab = @t, @var = @v
end
else if @i2 = 3
begin
set @v = 'utlysning_program_diarienummer'
exec sp_executesql
@stmt = @s,
@params = N'@tab as nvarchar(50), @var as nvarchar(50)',
@tab = @t, @var = @v
end
set @i2 = @i2 + 1
end
end
else
print('Nr: ' + cast(@i1 as char))
set @i1 = @i1 + 1
end
This script doesn't work. It runs through but have no outputs. If I declare @v
above the declaration of @s
it works, but then I need to declare @s
for every time I need to change the value for @v. Then there is no point in doing this.
@i1
iterates far more times than what is shown here.
The else statement to "if @i1" doesn't exist in the real script. It replaces a bunch of subloops that run for every value that is aloud for @i1 in this example.
I also tried to just execute @s like:
exec(@s)
in every loop. Same result.
So what am I missing?
Database engine is MS SQL Server.